Run a function/script in PHP and without affect the script flow - php

I need to make a php script that execute another function (or another script) in background: When i call it, the flow of the script must continue even if the second script is not finished.
I found http://php.net/manual/en/function.sleep.php (sleep function), but is not exactly what i need.
Some help?
Edit:
What i want to acomplish?
I need to make a change in my database. Then run a php script, but i need to make another change in my database 1 second (or whatever lapse) after i ran the php script.

Since you apparently don't care about a response from the script you are calling.
And if your server allow...
You could call your script as if it was from a shell and say that it should discard output with "> /dev/null 2>/dev/null &"...
shell_exec('php yourotherscript.php > /dev/null 2>/dev/null &');

Related

PHP exec() Command not Returning to Ajax Success function

Summary: I have a command that runs on a PHP page, called by Ajax.
Latest PHP example:
$linuxCmd = "cd ~/apps && node app.js > scr_log.log 2>&1 &";
exec($linuxCmd);
I've also tried:
$linuxCmd = "cd ~/apps && node app.js > scr_log.log 2>&1";
$linuxCmd = "cd ~/apps && node app.js &";
$linuxCmd = "cd ~/apps && node app.js > /dev/null 2>&1 &";
$linuxCmd = "cd ~/apps && node app.js 2>&1 /dev/null &";
And think over the past day I've covered every possible other combination of those commands. It seems that no matter what I've tried, the ajax success function on previous page does not run. I thought that running the process above in the background would let the PHP page return back to the ajax call on the javascript page and continue running scripts, but no luck.
I've also tried adding exit() and return() after the exec() function, but it's not reaching them.
Also, the script (app.js) runs in a loop. It is terminated when a value in the database changes as it checks that every time it runs in the loop. I also have a way to kill the process, which works fine and returns to the success function of that ajax request, because it just terminates the process.
To put it another way, I need the script that I'm running from PHP exec() to constantly run after started, but also need my front end javascript page to continue after starting that process in the backend.
I'm wondering if this is maybe not possible for some reason. And if so, if there is a better way than PHP's exec() function. Also tried shell_exec with a couple of the above combinations.
Tilde expansion is a function of the shell, not something intrinsic to Linux, so your script should not rely on it working. Even if that weren't the case, web servers generally run as a separate user that doesn't have a home directory. What you should do is use absolute paths throughout your script, and don't try to write into a user directory with the web server user.
<?php
$linuxCmd = "/usr/bin/node /home/user/apps/app.js > /var/log/scr_log.log 2>&1 &";
exec($linuxCmd);
Letting your web server write to /var/log may require some permissions tweaks, but best to put things where they belong. You don't want to give something exposed to the outside – like a web server – permissions to write into a sensitive location like a home directory.
As for how best to run the command persistently in the background, see the answers to this question. There's nothing in your code that would prevent an Ajax function from returning successfully; this would only happen if the address was wrong (i.e. 404) or an error occurred (e.g. 500.)

Is executing multiple PHP Scripts ran one at a time or simultaneously?

When executing multiple scripts within PHP using the exec command; are each script ran one at a time as in one after the other or are they ran simultaneously?
exec('/usr/bin/php -q process-duplicates.php');
exec('/usr/bin/php -q process-images.php');
exec('/usr/bin/php -q process-sitemaps.php');
Just want to make sure they are one after the other before attempting to rewrite my crontabs.
Sure, the only way to run at background is adding & to the command line arguments, which would put that exec()'d process into the background:
exec("php test.php &");
So you are right, they run one after the other.
NOTE: In your case you shouldn't use & as it will force to run all the scripts simultaneously.
exec waits for the script to return, see php.net
If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.
But as a devops, please please please do not run your cron jobs like this! Create entries in the crontab for each, or put them in a shell script and have cron run the script.

What exactly does this PHP code do? system("php ./somescript.php $something >/dev/null &");

system("php ./somescript.php $something >/dev/null &");
I'm new to PHP and I am deciphering someone else's code and can't figure out what this code is doing. I looked at the system documentation here so I understand that it will execute the PHP script in somescript.php, and that $something is a parameter passed to that script...but after that I'm lost.
Also, what part of the script does $something get passed to? How does it know what function in somescript.php to call first?
You are correct about it executing the script with $something passed as parameter. The > /dev/null is just piping the output into a black hole (i.e. suppressing it). The & part launches the script in the background.
system("php ./somescript.php $something >/dev/null &");
can be split up as:
system(
This is the php function to execute a command in shell
system("php
We are asking the php command line interpreter to be run
system("php ./
we are asking the interpreter to look in current directory using ./
system("php ./somescript.php
we are saying that the php file to be executed in somescript.php
system("php ./somescript.php $something
we are passing $something which is a variable in the script running system() as an argument into the script somescript.php
system("php ./somescript.php $something >/dev/null
we are saying that the output should be sent to /dev/null ..which basically means do not print any output on the screen. > is the redirection command. So > /dev/null means redirect output to /dev/null which is like an alias for a "null device" or simply..nothing.
system("php ./somescript.php $something >/dev/null &");
Lastly we are asking the script to be run in the background using & which means as soon as the script starts, control is returned back to the shell
It's basically running the ./somescript.php program, with $something as a command-line parameter.
It explicitly ignores the output by routing it to the null device.
And it runs it in its own shell and doesn't wait for it to finish (that's the & bit on the end).
I assume that somescript.php is a program that runs some kind of background task. It probably takes a bit of time to run, but your main program doesn't need to know about the results of that task, so it doesn't need to wait for it to finish.
[EDIT]
$something is passed into the program as a command-line argument. When PHP is called from the command line, the arguments are populated into the $argv array.
See the PHP manual for more info:
http://php.net/manual/en/reserved.variables.argv.php
http://php.net/manual/en/features.commandline.php
1 - system: execution of an external program from PHP
2- php ./somescript.php $something: PHP cli execution of a script called ./somescript.php with one argument being $something.
3 - >/dev/null: redirects stdout to /dev/null which means you won't see standard output, but you will still see stderr. More info on output redirections. That's pure UNIX nothing to do with PHP.
4 - &: sends command in the background so that PHP execution can continue without having to wait for the external program to complete. Once again, pure UNIX, nothing to do with PHP per se. More info.

child processes seperate from main process bash shell php

I' am calling sell script from my php code
with
foreach ($some_array) {
shell_exec(nohup $code);
}
like above
I want all shell_exec call to work independent from mail process which is php execution that we call shell script
But It's not working as I expected all shell_executions start right after previous one completed
So how can I make this shell_exec calls as independent child process that they don't wait each others completation
Thanks in advance
Add the '&' to the end of the command you want to execute so it works in background.
For a sequence of commands, enclose them within parentheses then append the & symbol but be sure to redirect stdout, stderr somewhere otherwise your script will hang waiting e.g.:
<?php
exec('( sleep 10; echo "finished" | mail ian#example.com ) &> /dev/null &');
?>
See http://us.php.net/manual/en/function.exec.php
Send them to the background
shell_exec("nohup somecommand &");
^---run job in background

PHP CLI process not terminating when done

I have this in one PHP file:
echo shell_exec('nohup /usr/bin/php -f '.CRON_DIRECTORY.'testjob.php > /dev/null 2>&1 &');
and in testjob.php I have:
file_put_contents('test.txt',time()); exit;
And it all runs just dandy. However if I go to processes it's not terminating testjob.php after it runs.
(Having to post this as an answer instead of comment as stackoverflow still won't let me post comments...)
Works for me. I made testjob.php exactly as described, and another file test.php with just the given line (except I removed CRON_DIRECTORY, because testjob.php was in the same directory for me).
To be sure I was measuring correctly, I added "sleep(5)" at the top of testjob.php, and in another window I have:
watch 'ps a |grep php'
running. This happens:
I run test.php
test.php exits immediately but testjob.php appears in my list
After 5 seconds it disappears.
I wondered if shell might matter, so I switched from bash to sh. Same result.
I also wondered if it might be because your outer script is long-running. So I put "sleep(10)" at the bottom of test.php. Same result (i.e. testjob.php finishes after 5 seconds, test.php finishes 5 seconds after that).
So, unhelpfully, your problem is somewhere other than the code you've posted.
Remove & from the end of your command. This symbol says nohup to continue running in background, thus shell_exec is waiting for task to complete... and waiting... and waiting... till the end of times ;)
I don't even understan why would you perform this command with nohup.
echo shell_exec('/usr/bin/php -f '.CRON_DIRECTORY.'testjob.php > /dev/null 2>&1');
should be enough.
You're executing PHP and make that execution a background task. That means it will run in background until it is finished. shell_exec will not kill that process or something similar.
You might want to set an execution limit, PHP cli has a setting of unlimited by default. See as well set_time_limit PHP Manual;
So if you wonder why the php process does not terminate, you need to debug the script. If that's too complicated and you're unable to find out why the script runs that long, you might just want to terminate the process after some time, e.g. 1 minute.

Categories