PHP Multi Process Asynchronous File Execution

As you now know, all of the codes in PHP are displayed on the page after they are executed. That is, the transaction will not be concluded until all of them are finished. There are some situations where you don't want this to happen. For example, you have an email newsletter list. And after sharing a topic, I will send you an e-mail to the list of 5000 people.

If you do this as soon as you share the post, there will be a waiting period on the page until the emails are sent. But what we want is to send it running in the background. Actually, we're going to write something very simple for it. First, let's create the php file that will send the mails. For example send-email.php.

sleep(5); // run after 5 sec

$postId = $argv[1];
// .. mailing processes etc.

Now, after publishing the post, it will be enough to run the following code;

exec('php -f send-email.php -- "5" > /dev/null 2>&1 &');

Of course, it is important to give the correct file path here. In this way, when our code runs, the 5 second wait part in send-email.php will not be reflected on the current page. While we have created our subject and continue to act without waiting, e-mails will continue to go in the background. Also, if you noticed, we sent a parameter to send-email.php in the exec() command. Incoming parameters are kept in the $argv variable. The value with index 0 is the name of the file, so use it starting from 1.

If you want to send more than one parameter;

exec('php -f send-email.php -- "5" "PHPEXAMPLE" "test" > /dev/null 2>&1 &');

You can send in the form. In send-email.php, you can access values as $argv[1] $argv[2] $argv[3].

Note: The exec() function is usually closed on hosting for security reasons. So try to use your own server, what is hosting anyway? Forget them :D

Good luck with.


There are no comments, make the firs comment