开发者

Asynchronous requests not working using fsock - php - Nginx

I have a php script which does the accepted answer described here.

It doesn't work unless I add the following before fclose($fp)

while (!feof($fp)) {
        $httpResponse .= fgets($fp, 128);
    }

Even a blank for loop would do the job instead of the above!!

But whats the point? I wanted Async calls :(

To add to my pain, the same code is running fine without the above code snippet开发者_高级运维 in an Apache driven environment.

Anybody knows if Nginx or php-fpm having a problem with such requests?


What you're looking for can only be done on Linux flavor systems with a PHP build that includes the Process Control functions (PCNTL library).

You'll find it's documentation here: http://php.net/manual/en/book.pcntl.php

Specifically what you want to do is "fork" a process. This creates an identical copy of the current PHP script's process including all memory references and then allows both scripts to continue executing simultaneously.

The "parent" script is aware that it is still the primary script. And the "child" script (or scripts, you can do this as many times as you want) is aware that is is a child. This allows you to choose a different action for the parent and the child once the child is spun off and turned into a daemon.

To do this, you'd use something along these lines:

$pid = pcntl_fork(); //store the process ID of the child when the script forks
if ($pid == -1) {
     die('could not fork'); // -1 return value means the process could not fork properly
} else if ($pid) {
     // a process ID will only be set in the parent script. this is the main script that can output to the user's browser
} else {
     // this is the child script executing. Any output from this script will NOT reach the user's browser
}

That will enable a script to spin off a child process that can continue executing along side (or long after) the parent script outputs it's content and exits.

You should keep in mind that these functions must be compiled into your PHP build and that the vast majority of hosting companies will not allow access to them on their servers. In order to use these functions, you generally will need to have a Virtual Private Server (VPS) or a Dedicated server. Not even cloud hosting setups will usually offer these functions as if used incorrectly (or maliciously) they can easily bring a server to it's knees.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜