Thursday, August 22, 2013

Using php execute command/run another php file wihtout waiting for result

<?php
session_start();
$_SESSION["student_name"] = "Pritom Kumar Mondal";

$_SESSION["roll"] = "College: 2150, Varsity: 060238";
echo "Start time: " date('h:i:s');
$phpCommandLocation "C:\\xampp\\php\\php.exe";
$phpFileLocation    "C:\\xampp\\htdocs\\test1\\call.php";
$logLocation        "C:\\tmp\\result.log";
$argvList = " session_id=".session_id(); /*You can send session id*/ 
$argvList.= " name=".rawurlencode("Pritom Kumar Mondal");
$command            $phpCommandLocation " -f "           .
    $phpFileLocation . $argvList " 1>>" $logLocation " 2>&1 &"; 
pclose(popen("start /B " $command"r"));
echo 
"<BR>End time: " date('h:i:s'); 

?>

And output is:
Start time: 11:07:26
End time: 11:07:26

And call.php looks like:
<?php
foreach($argv as $argvString) {
    $argvStringList = explode("=", $argvString);
    if($argvStringList[0] == "session_id") {
        session_id($argvStringList[1]);
        session_start();

        /* Start session with received session id, BINGO... */
    }
}
$string 
"\r\n-------------------------------\r\nStart time: " date('h:i:s'); 

$string .= "\r\nStart sleeping for 5 seconds."; 
sleep(5); 
$string .= "\r\nEnd time: " date('h:i:s');
 file_put_contents("data.txt" 
    "SOMETHING WENT GOOD...................\r\n" 
    $string);
echo 
$string; 

echo "\r\nReceived argv list: ";
print_r($argv); /* Printing argv as array */
echo "\r\nPrevious index.php session variables in currently executed php: ";
print_r($_SESSION); /* Printing argv as array */
?>
Yellow background showing that this script wait for 5 seconds.

The C:\\tmp\\result.log is:
-------------------------------
Start time: 11:07:28
Start sleeping for 5 seconds.

End time: 11:07:33
Received argv list: 
Array
(
    [0] => C:\xampp\htdocs\test1\call.php
    [1] => session_id=gjbf54ql8dhuvg0njsgt4hh8n7
    [2] => name=Pritom%20Kumar%20Mondal%2C%20Roll%3D2525

Previous index.php session variables in currently executed php:
Array
(
    [
student_name] => Pritom Kumar Mondal
    [roll] => College: 2150, Varsity: 060238
)


There are a few thing that are important here.

First of all: put the full path to the php binary, because this command will run under the apache user, and you will probably not have command alias like php set in that user.

Seccond: Note 2 things at the end of the command string: the '2>&1' and the '&'. The '2>&1' is for redirecting errors to the standard IO. And the most important thing is the '&' at the end of the command string, which tells the terminal not to wait for a response.

Third: Make sure you have 777 permissions on the 'result.log' file

If you use linux operating system just write:
<?php
exec
($command " > /dev/null &"); 

?>

No comments:

Post a Comment