首页 > 解决方案 > 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 请求都完成后再继续。我可以在这里做什么?

标签: phpcurl

解决方案


正如其他人所说,您的超时可能很小,并且添加 CURLOPT_RETURNTRANSFER 也可能会有所帮助,没有它,该值将不会出现在您的变量中

添加一些错误处理也会使调试更容易


if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

json 也可能会产生当前代码中不可见的错误

https://www.php.net/json-last-error


推荐阅读