I'm trying to use shell_exec()
and having hard time understanding how to use it. I referred to this page: Is there a way to use shell_exec without waiting for the command to complete?.
I created two PHP files:
shell_exec.php
<?php
shell_exec('php ' . __DIR__ . '/log.php > /dev/null 2>/dev/null &');
?>
log.php
<?php
$file = __DIR__ . '/log.txt';
$current = time() . ": sample text\r\n";
file_put_contents($file, $current,FILE_APPEND);
?>
Then I accessed the page of shell_exec.php from my browser. I expected that it runs log.php and creates a file. However, nothing happens.
I suspect that the php paths specified in the function, which is php
in the above code, is different in different operating system. I'm currently testing in Windows, so that may be the reason that it doesn't work. But I'm not 100% sure.
If so, how can I find the php path and specify it in my environment? Also does that mean that if I distribute a script which uses shell_exec()
and call a php script, do I have to write some code to find out the php path? In that case, is there a good way of doing it?
If so, how can I find the php path and specify it in my environment? Also does that mean that if I distribute a script which uses shell_exec()...
Unfortunately, yes. The environment where you distribute the script must have a command line PHP (which is not necessarily the same as the PHP used by the Web server - it might be a different version).
And there is no easy way of "finding" it.
So what you would need to do is, you clearly state (when distributing) that PHP command line executable must be in the PATH.
At that point, shell_exec('php -q -f yourfile...') ought to work.
You can redirect the output to a file (always the same if you want) and delete it if there are no errors. Otherwise the file will show what errors occurred, which may be useful.
UPDATE: and the first times, to debug, don't redirect the output, but try:
<?php
Header("Content-Type: text/plain");
error_reporting(E_ALL);
print shell_exec('php "' . __DIR__ . '/log.php" 2>&1'); // > /dev/null 2>/dev/null &');
?>
This way you can see if the command hits some other snag, such as not having the rights to create the log.txt file in the first place.