简体   繁体   中英

PHP Script is not waiting for curl response

My PHP script is continuing to run even though there is a live curl request. I am sending an array to an external website for processing via curl.

I've tried modifying curl options and setting max_execution_time in php.ini and set_max_time(0) in my scripts and these have yielded no results.

    $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;
}

I want my script to wait until all curl requests have been completed before continuing. What can I do here?

As stated by others your timeout might be to small, and adding the CURLOPT_RETURNTRANSFER might help as well, without it, the value will not end up in your variable

adding some error handling will make debuging easyer as well


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

The json might also produce errors not visible in you current code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM