php - PHP 脚本不等待 curl 响应
问题描述
即使有实时 curl 请求,我的 PHP 脚本仍在继续运行。我正在向外部网站发送一个数组以通过 curl 进行处理。
我尝试在脚本中修改 curl 选项并在 php.ini 和 set_max_time(0) 中设置 max_execution_time,但这些都没有产生任何结果。
$postfielddata = array(
'action' => 'masscreate',
'type' => $type,
'fields' => $fields,
'sessiontoken' => $_POST['sessiontoken'],
);
//I expected this to pause the script until all data in the $post variable has been processed on the external website
//external website that is being curled runs fine with other large operations
$result = $this->runCurl($postfielddata);
error_log("response from api: " . print_r($result));
if (!$result)
{
//this block executes immediately, not waiting for curl to finish above
error_log("here no result so redirect error");
$this->redirect_error($type, 'Invalid file uploaded.', $data);
return;
}
//curl function that is being called
private function runCurl($postfielddata)
{
$post = array( 'data' => json_encode($postfielddata) );
$url = $this->config->item('urlToCurl');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($post));
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($post) );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 400);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
$result = json_decode($result, true);
curl_close($ch);
return $result;
}
我希望我的脚本等到所有 curl 请求都完成后再继续。我可以在这里做什么?
解决方案
正如其他人所说,您的超时可能很小,并且添加 CURLOPT_RETURNTRANSFER 也可能会有所帮助,没有它,该值将不会出现在您的变量中
添加一些错误处理也会使调试更容易
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
}
json 也可能会产生当前代码中不可见的错误
推荐阅读
- python - 树中节点的初始化(Python)
- css - 在 CSS 网格布局中使用 Angular *ngFor?
- java - 如何在输入和输出流中使用 for 循环?
- unity3d - 相对于 azure 空间锚点放置内容
- bash - 运行多个命令并在其中一个失败时让脚本失败
- android - 带有圆帽的笔画在 EditText 中显示一半
- php - 如何在本地环境中向手机发送短信?
- python-3.x - 无法使用 TensorFlow 数据集拆分疟疾数据集
- javascript - 使用 tsconfig.json 从 node_modules 导入外部类型定义
- android - 这个广告倒计时方法是如何通过 jadx 从 apk 工作的?