Codingalien
Codingalien

Reputation: 3037

How to check API request timeout by using Curl?

I have a scenario. Here I'm using Curl for accessing an API. If API is not accessible, I have to send an alert email. So how can I check, if there is a request timeout?

Here is my code.

    $alerthttp1 = array();
    $string = 'somestring';
    $key = md5($string);
    $service_url = 'www.someurl.com/'.$key;

    $curl = curl_init($service_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 300);
    $curl_response = curl_exec($curl);
    $curl_errno = curl_errno($curl);
    $curl_error = curl_error($curl);

    error_log(json_encode($curl_errno));
    error_log(json_encode($curl_error));

    if(curl_error($curl) || $curl_response === false || $curl_errno > 0)
    {
        $info = curl_getinfo($curl);
        hlog_errorlog('error occured during curl exec - ' . var_export($info));
        hlog_errorlog('error -----------> '. $curl_error); 
        curl_close($curl);

        $alerthttp1[] = array('status' => 'FAILED');//for email alert
    }

Please suggest me, the best way of coding.

Thank you

Upvotes: 2

Views: 2062

Answers (2)

No you can't know it with CURL. Ask on API support. Or choose timeout time yourself. Usually it's 30 second.

Upvotes: 0

Sumit Kumar
Sumit Kumar

Reputation: 580

Try to use CURLOPT_CONNECTTIMEOUT instead CURLOPT_TIMEOUT CURLOPT_CONNECTTIMEOUT is the maximum amount of time in seconds that is allowed to make the connection to the server.

Upvotes: 2

Related Questions