PHP Curl异步响应 [英] PHP Curl async response

查看:78
本文介绍了PHP Curl异步响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP文件,该文件通过curl调用另一个PHP文件。我试图让第二个文件将响应发送回第一个文件,以使其知道它已开始。问题是第一个不能等待第一个完成执行,因为这可能需要一分钟或更长的时间,我需要它立即发送响应,然后再处理常规业务。我尝试在第二个文件的顶部使用回显,但第一个没有得到响应。
如何发送未完成执行的响应?

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
.
.
.
?>

当我运行file1.php时,结果为:响应:但我希望它是响应:我开始了。'我知道file2.php被启动是因为执行了'Other CODE',但是回声没有被发送回file1.php,为什么?

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?

推荐答案

答案最终是CURL的行为不像浏览器:

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

PHP Curl输出缓冲区未收到响应

我首先运行第二个文件,然后运行第二个文件。第二个文件等待完成文件写入,显然第一个文件完成了写操作。

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.

这篇关于PHP Curl异步响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆