PHP Curl async response

2019-03-21 23:27发布

I have a PHP file that invokes another PHP file via curl. I am trying to have the second file send a response back to the first to let it know that it started. The problem is the first can't wait for the first to finish execution because that can take a minute or more, I need it to send a response immediately then go about it's regular business. I tried using an echo at the top of the second file, but the first doesn't get that as a response. How do I send back a response without finishing execution?

file1.php

<?php
$url = 'file2.php';
$params = array('data'=>$data,'moredata'=>$moredata);

$options = array(
    CURLOPT_RETURNTRANSFER => true,     // return web page
    CURLOPT_HEADER         => false,    // don't return headers
    CURLOPT_FOLLOWLOCATION => true,     // follow redirects
    CURLOPT_ENCODING       => "",       // handle all encodings
    CURLOPT_USERAGENT      => "Mozilla", // who am i
    CURLOPT_AUTOREFERER    => true,     // set referer on redirect
    CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
    CURLOPT_TIMEOUT        => 120,      // timeout on response
    CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
    CURLOPT_TIMEOUT        => 10,        // don't wait too long
    CURLOPT_POST           => true,     // Use Method POST (not GET)
    CURLOPT_POSTFIELDS     => http_build_query($params)
);
$ch = curl_init($url);

curl_setopt_array( $ch, $options );
$response = curl_exec($ch); // See that the page started.
curl_close($ch);
echo  'Response: ' . $response;
?>

file2.php

<?php
/* This is the top of the file. */
echo 'I started.';
.
.
.
// Other CODE
.
.
.
?>

When I run file1.php it results in: 'Response: ' but I expect it to be 'Response: I started.' I know that file2.php gets started because 'Other CODE' get executed, but The echo doesn't get sent back to file1.php, why?

2条回答
可以哭但决不认输i
2楼-- · 2019-03-21 23:57

This could be just what you're looking for. Forking in PHP:

http://framework.zend.com/manual/en/zendx.console.process.unix.overview.html

A process divides in two. One is father of the other. The father can tell the client he just begun and the child can do the job. When the child finishes, he's able to report the father which can also report to the client.

Keep in mind there are many requirements for this to run:

  • Linux
  • CLI or CGI interface
  • shmop, pcntl and posix extensions (require recompiling)
查看更多
乱世女痞
3楼-- · 2019-03-22 00:21

The answer ended up being that CURL does not behave like a browser:

PHP Curl output buffer not receiving response

I ended up running my 2nd file first and my 1st file second. The 2nd file waited for a 'finished' file write that the 1st file did once it, obviously, finished.

At this point, it seems like the database would be a better place to store messages for files to be able to pass between each other, but a file would also work for a quick and dirty job.

查看更多
登录 后发表回答