0

I using url to request remote urls that sometimes may very slow or just down. In this case, my php scripts still waiting for the response, it makes apache has to many requests stay in memory and then overload. I need a way to stop curl requesting or stop running php script when specified time passed. I'd tried declare(), it makes no sense for curl. Can someone know how to solve it?

BTW: what is the effect of CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT?

Here is code sample:

function http($url, $method, $postfields = NULL) {
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ci, CURLOPT_TIMEOUT, 5);
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
    curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, 0);

    switch ($method) {
    case 'POST':
        curl_setopt($ci, CURLOPT_POST, TRUE);
        if (!empty($postfields)) {
            curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
        }
        break;
    case 'DELETE':
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
        if (!empty($postfields)) {
            $url = "{$url}?{$postfields}";
        }
    }

    curl_setopt($ci, CURLOPT_URL, $url);
    $response = curl_exec($ci);
    $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    $this->last_api_call = $url;
    curl_close ($ci);
    return $response;
}

I set the connecttimeout and timeout to 5s, but it dosen't workd. Curl still spend a long time to finish the request, but the url if not response in 5s, that means it's down or the network condition is bad, should stop it.

1
  • 1
    Setting a timeout is the common solution to this. What's the problem with CURLOPT_TIMEOUT? You may want to add some code and a description what doesn't work if you want help with that. Commented Mar 26, 2010 at 10:21

1 Answer 1

1

CURLOPT_CONNECTTIMEOUT will stop the request if connection still has not been established after the specified time

CURLOPT_TIMEOUT will stop the request if complete response has still not been received after the specified time

For me I sometimes I have problems where it still doesn't time out itself, in this instance you could try something like this:

declare(ticks = 1);

function sig_handler($sig) {

 mysql_query("insert into log (event) values ('Timed out!')");
 die("Timed out!");

}

pcntl_signal(SIGALRM,"sig_handler");
// call sig_handler function after 30 seconds
pcntl_alarm(30);

// curl code here
Sign up to request clarification or add additional context in comments.

1 Comment

I can't test with pcntl, server dosen't support it. Thanks all the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.