r/PHPhelp • • Jun 06 '21

Can I tell PHP to use less cpu?

10 Upvotes

My server is old and runs some code that updates every few minutes. I now have a long PHP program I need to run on some files, it will take a few hours to complete.

Is there any way to run this new program "slowly" or in the background or low priority or something so the server can still function normally and the code just completes it's task without grinding the server down?


r/PHPhelp • • Apr 20 '21

My PHP laravel site got hacked, database stolen and is being held ransom

10 Upvotes

I have a project in which the dev left halfway. Am not a dev. Today i found out that my database got deleted and this was left in its place-
"To recover your lost databases and avoid leaking it: visit http:// o42xfh5kao7mrtesnok5jgdsfagjsgzxlxdlpkpd2x6lpckhzk225yad. onion and enter your unique token (*** hidden for my security) and pay the required amount of Bitcoin to get it back. Databases that we have: (my databse name). Your databases are downloaded and backed up on our servers. If we dont receive your payment in the next 9 Days, we will sell your database to the highest bidder or use them otherwise. To access this site you have use the tor browser https://www.torproject.org/projects/torbrowser.html"

I have an auto backup on my server from 11 april and i used that and the site went upagain. But after a few hours- same thing. Any ideas on what to do?

I dont care about them having my DB. But I want to close the backdoor through which they enetered. So that i can just use the autobackup and the site can go up again.


r/PHPhelp • • Mar 01 '21

Can't get my head around mvc and routing

10 Upvotes

I've been programming for a pretty long time (around 4 years now) and have made baby steps since. I'm the type of person where the lightbulb has to go on in the head in order to fully understand something. I'm learning this very slow due to programming being a hobby and placing social life on the first place.

Now that we're in a lockdown, and because of it I don't have to worry about social life anymore, I wanted to step it up again. Always used procedural php because that's just easy, but wanted to learn the mvc model. Now this is where I just can't get my head around. Everyone is explaining it different and some sources are just hard to follow imo. Does anyone know an easy to follow guide tutorial or something that explains this well?

Also, just as a sanity check: Model: handles all database traffic and gives data to the view View: shows content to the user and gets data from the model. Controller: gets user input and passes it to the model which puts it in the database.

Is this correct?

Thanks!


r/PHPhelp • • Feb 26 '21

Is cURL the best way to connect to an API using PHP?

10 Upvotes

What other options are there? What are their pros and cons?


r/PHPhelp • • Jan 03 '21

Answer to: How to get the distance between two gps points in php

10 Upvotes

I needed a quick solution to get the distance between two gps points, so I made my own and hopefully it will help you.

function measureDistance($lat1, $lon1, $lat2, $lon2){
    $distance = rad2deg(acos(sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 - $lon2)))) * 60 * 1.1515;
    // miles to km
    // $distance = $distance * 1.609344;
    return $distance;
}

r/PHPhelp • • Dec 25 '20

First time building a job queue. Does this make sense?

10 Upvotes

I need to create a queue for my project but I am not totally sure how. My thought was, I could just add a mysql table for jobs, and run a cron job to check for new jobs every minute. Something like this:

// my cron process

// if there is a job with a status of "in-progress"
    // do nothing
// else
    // are there any jobs? get the oldest job in the table
    // update the status to "in-progress"
    // do whatever the job tells you
    // delete the job

So that would basically run every minute. Is this an acceptable way to build a queue from scratch? I know running a job every minute may not be fast for some use cases but I think it is ok in my case.

Edit: I have been reading about RabbitMQ. Would this be a better option?

Edit2: If someone could explain to me why I got downvoted I would appreciate it. I seem to get downvoted immediately almost all the time so I want to know what I am doing wrong.

Edit3: Thanks everyone for the advice. I have learned a lot about queues and I think my final solution will be something along the lines of this:

/** THIS IS WHAT MY JOBS TABLE LOOKS LIKE */
// $sql = "CREATE TABLE IF NOT EXISTS `QueuedFileTransfers` (";
// $sql .= "`id` int(11) NOT NULL AUTO_INCREMENT, ";
// $sql .= "`file_name` VARCHAR(20) DEFAULT NULL, ";
// $sql .= "`status` VARCHAR(20) DEFAULT NULL, ";
// $sql .= "`attempts` INT DEFAULT NULL, ";
// $sql .= "`additional_data` VARCHAR(20) DEFAULT NULL, "; // store any relevant json data if the job fails
// $sql .= "`admin_notified` TINYINT(1) DEFAULT 0, "; 
// $sql .= "`job_started_on` TIMESTAMP DEFAULT NULL, ";
// $sql .= "`job_finished_on` TIMESTAMP DEFAULT NULL, ";
// $sql .= "`created_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, ";
// $sql .= ") ENGINE = INNODB";

// check if there is a job that has been running for a long time, possibly stuck
// if there is a job with a status of "in-progress" and job_started_on > 15 min ago
    // ??????

// check if there are any failed jobs to retry
// if there are any job with a status of "failed" and attempts < 3 
    // processJob($job);

// else if there is a job with a status of "pending", get the oldest one
    // processJob($job)


// function processJob($job) {
    // update job status to "in-progress" and job_started_on and attempts++
    // check  effected rows to make sure it updated
    try {
        // do the job
        // update status to "completed"
    } catch (Error $e) {
        // change status to "failed"
        // append error data to additional_data column
        // if attempts = 3
            // send email to administrator
            // update admin_notified to 1
    }
// }

Except refactored into OOP


r/PHPhelp • • Oct 23 '20

After years of Laravel, I want to learn MySQL instead of using magic to access the database, should I use PDO or DBAL?

10 Upvotes

r/PHPhelp • • Aug 21 '20

Launch countdown for a website.

10 Upvotes

I have a website that launches on 28th @ 12:00 gmt.
Until that time, I want my page to display a countdown page.

Currently I have a html -page with a javascript -snippet that displays the countdown,
and when the counter reaches zero, it redirects to the real page.

Problem is that my javascript counter uses date(), which gets the time from client machine,
so you can fake your system time and get past the countdown- page.

What would be an efficient and sure way to prevent anyone from viewing my page before launch?


r/PHPhelp • • May 19 '20

Login php not working, giving me error code wrongpswd1 althoug my pwd and user is correct thank you in advance for your help and time

10 Upvotes
<?php 
    if(isset($_POST['login-submit'])){
     require 'config.inc.php';
    $mailuid = $_POST['mailuid'];
    $password = $_POST['pwd'];
   if (empty($mailuid)|| empty($password)){
     header("Location:../index.php?error=emptyfields");
     exit();
    }
    else { 
        $sql = "SELECT * FROM user_account WHERE uidusers = ? OR emailusers = ?;";
        $stmt = mysqli_stmt_init($conn);
        if(!mysqli_stmt_prepare($stmt, $sql)){
            header("Location:../index.php?error=sqlerror");
     exit();
        }
        else {
           
            mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
            
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);
            if($row = mysqli_fetch_assoc($result)){ 
                $pwsdcheck = password_verify($password, $row['pwdusers']);
                if($pwsdcheck == false){
                    header("Location:../index.php?error=wrongpwsd1");
                    exit();

                }
                else if ($pwsdcheck == true) {
                    session_start();
                    $_SESSION['userid'] = $row['id'];
                    $_SESSION['useruid'] = $row['uidusers'];
                    
                    header("Location:../main.php?login=success");
                    exit();
                }
                else {
                    header("Location:../index.php?error=wrongpwsd");
                    exit();
                }


            }
           else {
            header("Location:../index.php?error=nonexistinguser");
            exit();
           }
        }

    }
}
else {
    header("Location:../index.php");
    exit();
}

r/PHPhelp • • May 14 '20

Creating a 2 factor authentication system

10 Upvotes

I'm trying to build a very simple authentication system by sending a temporary code via e-mail. I would like to know if you see any major flaws with this workflow:

  1. user logs in with username and password

  2. a temporary code gets generated, hashed and stored in the database row for that user

  3. an e-mail with the unhashed code gets sent

  4. the user enters the code and it is compared to the de-hashed code from the database

  5. the user gets access and everyone lived happily ever after


r/PHPhelp • • May 11 '20

Unit/Integration testing advice needed

10 Upvotes

My situation: working in a company, we have one big main project and a couple of microservices. We, like everyone else, have some issues. One of them is lack of tests. I am pushing to write more tests, but it's a bit hard, especially on existing project where people are not used to writing tests. I know what the difference between unit, integration, acceptance tests is, that's not my issue.

Since I started digging, I noticed that most of our business logic relies of data from the db. Examples:

  • if the customer is of this type - do this thing, otherwise something different

  • if the customer has orders which has specific type of product, do something

  • and a lot of more complex relationships, like if a customer of specific type, has any orders for the past month that contain specific items which are in specific state, and these items don't have stock... you get the point

This is textbook integration test logic right there. I know that in the perfect scenario I should have a "testing db" and a "testing db dump" that gets cleaned and repopulated after each test, but how do you deal with the most complex cases like the ones I described? Does it make sense to populate so much different related data after each test? Wouldn't that be super slow at some point? Not to mention the amount of work it'll take to keep this testing db up-to-date. If not, what are some other solutions? We are using Codeception, but my question is more general.

P.S. Thanks to everyone who'd read that wall of text. I tried to be as descriptive as possible.


r/PHPhelp • • Feb 12 '20

Is PHP still relevant in 2020 and beyond?

10 Upvotes

Hello all, I'm graduating in the end of this year and I love PHP. I've been working in PHP since few years and I've done almost all of my projects in PHP. I just happened to have a class with a professor who works for private IT company and he hates PHP. He strictly orders us not to use PHP in projects or in fact, not use at all. Every single day he bullies PHP, finds its faults and that scares the hell out of me because I'm almost at the end now. I know other languages but PHP makes me work harder, it's fun to program in PHP and it's kind of becoming my hobby to learn new things in PHP. So, my question is for all the people who are working in the IT industry right now. I would much appreciate it if you could please advise me on this.

Is it relevant? For how many more years? Should I stop working in PHP? What can I learn in few months that can give me a job after I graduate?

Thank you in advance!


r/PHPhelp • • Sep 14 '19

Laravel - what is it and why

10 Upvotes

Hey all! I'm not a newbie to PHP, but I am a newbie to frameworks like Laravel, and I'm having extreme difficulty wrapping my head around it... All the Laravel website says is that "Laravel is a web application framework with expressive, elegant syntax".

A framework for what? What does it do? Why does someone use Laravel over just straight up coding it... I can write expressive, elegant syntax too, so what's different? Is Laravel a different language that's built on PHP? Or is it PHP? Is it MVC? As you can see, I'm so confused!!!

Apparently, most php developers are supposed to know Laravel nowadays, but I'm completely stumped! Thanks for the help anyone can give me!


r/PHPhelp • • Aug 20 '19

How did you learn the different design patterns?

10 Upvotes

I trying to improve my oop and I starting to read about the different design patterns but its not quite sinking in!

Any tips or real world examples that you can point me to that might help?


r/PHPhelp • • May 22 '18

Transition to OOP

10 Upvotes

I’m pretty confident with procedural PHP and can achieve just about anything I want this way, but I realised a long time ago that this is far from the most efficient way to be working, especially as my projects get bigger. I need to get confident with OOP.

I've done some basic tutorials and am getting a grasp of the concepts; classes, methods etc. but fall down when it comes to utilising them in a realistic structure/real world environment.

I tend to find my learning is most effective when I start simple and expand. So ideally, I would love to get hold of a relatively simple OOP based project and add functionality/features to build it up.

Is anybody aware of such a project/tutorial? Everything seems to be aimed at absolute novices (explaining variable types etc.) or those who already have a solid grasp of basic OOP. I'm having a hard time finding resources for intermediates.


r/PHPhelp • • Jan 28 '18

Is MVC too hard to learn??

10 Upvotes

I'm learning it from past couple of days and still confused.

I'm a noob, so please tell me is it natural?? Or maybe there is some problem in my way of learning??


r/PHPhelp • • Jan 09 '18

Whats the point of __construct?

10 Upvotes

I understand it changes objects, by why wouldn't you just edit the code to do that?


r/PHPhelp • • Nov 02 '17

Why PHP is not used as a scripting language for automation unlike python/perl?

10 Upvotes

For what reasons, python and perl have become the standard for writing automated scripts for Windows and Linux, as much as bash language or WSH platform languages, while PHP remained the language for writing server-side code only? Today, many linux distributions include a python in the standard delivery, the python is used even for writing desktop gui programs. At the same time, the main products for PHP in this direction (PhpQt, GTK-PHP, PHP Devel Studio, etc) is abandoned/doesn't under development.

Why? What are the reasons for the inconvenience of using PHP as a general-purpose or, at least, a system scripting language, not only for server-side code? And why these problems are solved in other languages, but not in the PHP, despite its popularity? Is it a developer's policy, architecture and implementation constraints, or is it only for historical reasons?

Finally, please correct me if I'm wrong, give any examples of using PHP as a scripting language in real projects, examples of literature that describes the use of PHP in this way.


r/PHPhelp • • Mar 27 '17

Disqus replacement.

10 Upvotes

I'm currently using Disqus in one of my sites for user discussions. It's working great but I would love to use an open source solution.

Is there one that someone can recommend?


r/PHPhelp • • Feb 04 '17

New to PHP but not web development

10 Upvotes

I've built a handful of apps with Node worked a little with Python/Django and. I've been wanting to learn Php because it being the industry standard but don't want to waste time with beginner "Hello World" examples. What are some good resources and tutorials for building useful and interesting things?

I feel like once I pick up the syntax, I'll be okay, but maybe I'm over-simplifying it. People who've used other languages--what are things to be wary of when coming to Php from a different background?


r/PHPhelp • • Jan 31 '17

Explain to me like I am 5....

10 Upvotes

I am trying to understand form submission. More specifically, I am developing a website with just HTML5 and CSS3 (I am brand new to building websites) and I want to put a contact page in it, however, when I read about contact pages, php always shows up, and I am brand new to this and I just need some guidance. Can someone point me in the right direction for me to figure this out? Is there a video series? A best book or article to read?

Doing this kind of thing has just peaked my interest the last few weeks and after sitting down and looking at a few sites and videos, I think that I can be good at it.

I need some mentors, I am trying to research as much as I can. Any help at all is appreciated!


r/PHPhelp • • Aug 09 '16

Modern PHP - What should I know/Learn about?

10 Upvotes

I want to make sure that my skills are up to date with PHP and I wanted to ask what should a modern PHP developer know?

Currently Im looking into/brushing up on:

  • PHP 5.6 / PHP 7 versions

  • Composer

  • Laravel

  • Symfony

  • PDO/Mysql/Sqlite3

Im trying to build various things using these technologies - what other things should I look at?


r/PHPhelp • • Aug 06 '16

What is the best way to port PHP 5.3 codebase to PHP 7?

10 Upvotes

This old codebase I inherited has all kinds of issues (magic quotes etc). I'd like to port it to PHP 7.

Are there any guidelines to help me with this task?

Are there any tools that can partly/fully automate this - doing static analysis, giving recommendations etc?

Any tutorials, links etc would be very helpful too


r/PHPhelp • • Aug 03 '14

PHP Porn Scraping trend bot (PROBABLY NSFW) NSFW

10 Upvotes

So before I start, please don't judge me.

I got bored one day and built a thing to scrape the PornMD get search term thingy and it all just escalated from there.

<?php


$str = file_get_contents("http://www.pornmd.com/getliveterms");


$text = preg_replace("/[^a-zA-Z0-9]+/", " ", $str);

$replacer1 = array('segment t keyword','segment s keyword','segment g keyword');
$replacer2 = array('','','');
$combine = str_replace($replacer1, $replacer2, $text);

$brmaker = str_replace('  ','</br>',$combine);

$brexplode = explode("</br>", $brmaker);

$txtfile = implode($brexplode,"\r\n");
file_put_contents("output.txt", "\n".$txtfile,FILE_APPEND);

$output = file('output.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach(array_count_values($output) as $key=>$value){
if ($value > 1){
echo $key . '<br>';
 }
}
?>

So basically as you can see I've got it printing duplicate entries in the auto updating text file,

What I'm really looking to do is have it print the top 10 most duplicated results and show how many times they're duplicated... Anyone have anyone have any idea how I'd do this?

Thanks guys (I'm not weird I swear).

Edit: Got everything working, thanks guys. I'll leave this post up in case anyone wants to use my code.