我有一个用PHP编写的API,用CURL发送10个请求。 问题是,当我向API发送HTTP请求时,尽管服务器尚未完成工作(获得所有10个请求的响应),但我立即得到响应。我不能使用ignore_user_abort()
,因为我需要准确知道API完成的时间。PHP持有请求,直到完成
如何通知连接“嘿,等待脚本完成工作”?
重要说明:如果我使用sleep()
,则连接成立。
这里是我的代码:gist
我有一个用PHP编写的API,用CURL发送10个请求。 问题是,当我向API发送HTTP请求时,尽管服务器尚未完成工作(获得所有10个请求的响应),但我立即得到响应。我不能使用ignore_user_abort()
,因为我需要准确知道API完成的时间。PHP持有请求,直到完成
如何通知连接“嘿,等待脚本完成工作”?
重要说明:如果我使用sleep()
,则连接成立。
这里是我的代码:gist
这只是说明如何ob_start作品的例子。
echo "hello";
ob_start(); // output buffering starts here
echo "hello1";
//all curl requests
if(all curl requests completed)
{
ob_end_flush() ;
}
无代码引用,我只能显示ob_start的实现。您必须根据您的要求更改此代码。
$handlers = [];
$mh = curl_multi_init();
ob_start(); // output buffering starts here
foreach($query->fetchAll() as $domain){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://'.$domain['name']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $DEFAULT_REQUEST_TIMEOUT);
curl_setopt($ch, CURLOPT_TIMEOUT, $DEFAULT_REQUEST_TIMEOUT);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
curl_multi_add_handle($mh, $ch);
$handlers[] = ['ch'=>$ch, 'domain_id'=>$domain['domain_id']];
echo $domain['name'];
}
// Execute the handles
$active = null;
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
// Wait for activity on any curl-connection
if (curl_multi_select($mh) == -1) {
usleep(1);
}
// Continue to exec until curl is ready to
// give us more data
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
// Extract the content
$values = [];
foreach($handlers as $key => $handle){
// Check for errors
echo $key.'. result: ';
$curlError = curl_error($handle['ch']);
if($curlError == ""){
$res = curl_multi_getcontent($handle['ch']);
echo 'done';
}
else {
echo "Curl error on handle $key: $curlError".' <br />';
}
// Remove and close the handle
curl_multi_remove_handle($mh, $handle['ch']);
curl_close($handle['ch']);
}
// Clean up the curl_multi handle
curl_multi_close($mh);
ob_end_flush() ; // output flushed here
是的,但是如何知道所有请求何时完成? –
它是:[链接到代码](https://gist.github.com/CodingAspect/c9599f0675aa4aa2268c) –
你从API得到有何反应? –
更好的是,你能告诉我们你的代码到目前为止? –
@ Jan.J&Aedix我用代码的链接更新了问题。 –