Search code examples
phpexecnohuppassthru

PHP exec whit nohup works on commandline but not on http calls


I've have this script who run another one in the background, without waiting to it to finish.

My script.php:

$cmd = "nohup php script2.php > /dev/null 2>&1 &";
exec($cmd);

My script2.php:

sleep(10);
mail("[email protected]","test","ok");

If I run it in commandline, it works fine: the call finish inmediately and I get a new mail in my inbox after 10 seconds.

But if I call to my script with http://myserver/script.php, I don't receive anything.

Notice that using:

$cmd = "php script2.php > /dev/null 2>&1";

works in both calling methods. So there's something wrong with the http call and the use of nohup.

I also tried passthru and shell_exec instead of exec with the same results.

Also tried this just in case, but it didn't work in any case.


Solution

  • Create a file on your server called phpinfo.php.

    This file will only have one line of code:

    <?php echo phpinfo() ?>
    

    If you're uncertain, there is a full tutorial here: http://www.inmotionhosting.com/support/website/php/create-phpinfo-page-to-see-php-settings A lot of hosting companies may disable exec() and you may be unable to change your php.ini file.

    If so, your best bet would be to start with the php mail function. http://php.net/manual/en/function.mail.php

    Additional Information about php.ini: Your original statement that it works from the command line but not from a call through the browser makes, to me, the php.ini directives the most likely culprit. When PHP is executed through a webserver, the execution of any script is dictated by these directives. The best reference is the PHP documentation: http://php.net/manual/en/ini.core.php. If you run the phpinfo.php from a browser on your server, you're looking for a section "Core" and within that the disable_functions table row.

    On my development server, there are a lot of functions that are disabled; including exec() and fork().

    If you can edit your php.ini file, you can remove the exec function from the line

    disable_functions = 
    

    and restart your webserver; although I would discourage it. That function is disabled for valid security reasons.