2015-01-16 32 views
0

有时我有一个很长的任务,我不希望当前的PHP线程等待,我做了如下的事情。在会话中传递数据有点不方便,但似乎有效。发送数据到php后台线程脚本

我有另一个类似的应用程序,除了file1.php没有被用户的客户端访问,而是被另一个服务器访问,并且用户只能访问其他服务器。因此,会话cookie将不可用于file1.php中的session_start(),并且它必须为每个事件创建单独的会话文件。

将数据传递给后台工作者脚本的其他选项是什么?我没有传递大量的数据,但它仍然是1kb左右。

file1.php

session_start(); 
$_SESSION['_xfr']=$_POST; 
$status=exec($'/usr/bin/php -q /path/to/my/worker.php'.' '.session_id().' >/dev/null &'); 
echo('Tell client we are done.'); 

file2.php

session_id($argv[1]);//Set by parent 
session_start(); 
$data=$_SESSION['_xfr']; 
//Do some task 

回答

1

您只需通过ARGS发送数据,为JSON:

file1.php

$status=exec($'/usr/bin/php -q /path/to/my/worker.php'.' '.json_encode($_POST).' >/dev/null &'); 
echo('Tell client we are done.'); 

file2.php

$data=json_decode($argv[1]); 
//Do some task 
+0

可以发送多少数据作为参数? – user1032531

+0

@ user1032531超过1kb我期望:http://stackoverflow.com/questions/6846263/maximum-length-of-command-line-argument-that-c​​an-be-passed-to-sqlplus-from-lin – Steve

1

如果目标是将状态返回给客户端并继续处理,那么您可能会发现简单地执行类似操作更容易。

public function closeConnection($body, $responseCode){ 
    // Cause we are clever and don't want the rest of the script to be bound by a timeout. 
    // Set to zero so no time limit is imposed from here on out. 
    set_time_limit(0); 

    // Client disconnect should NOT abort our script execution 
    ignore_user_abort(true); 

    // Clean (erase) the output buffer and turn off output buffering 
    // in case there was anything up in there to begin with. 
    ob_end_clean(); 

    // Turn on output buffering, because ... we just turned it off ... 
    // if it was on. 
    ob_start(); 

    echo $body; 

    // Return the length of the output buffer 
    $size = ob_get_length(); 

    // send headers to tell the browser to close the connection 
    // remember, the headers must be called prior to any actual 
    // input being sent via our flush(es) below. 
    header("Connection: close\r\n"); 
    header("Content-Encoding: none\r\n"); 
    header("Content-Length: $size"); 

    // Set the HTTP response code 
    // this is only available in PHP 5.4.0 or greater 
    http_response_code($responseCode); 

    // Flush (send) the output buffer and turn off output buffering 
    ob_end_flush(); 

    // Flush (send) the output buffer 
    // This looks like overkill, but trust me. I know, you really don't need this 
    // unless you do need it, in which case, you will be glad you had it! 
    @ob_flush(); 

    // Flush system output buffer 
    // I know, more over kill looking stuff, but this 
    // Flushes the system write buffers of PHP and whatever backend PHP is using 
    // (CGI, a web server, etc). This attempts to push current output all the way 
    // to the browser with a few caveats. 
    flush(); 
} 

否则,你的选择是有限的多线程的HTTP服务器,并通过EXEC脱壳而出,你在做它的其他方式去......然而,你可能想NOHUP命令,而不是简单地运行它作为当前线程的子进程。

+0

是目标。我将需要测试它。谢谢 – user1032531

+0

我认为这是最好的解决方案,并希望我可以不止一次地提升它。然而,另一个答案回答了我的具体问题。 – user1032531