tags:

views:

286

answers:

1

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.

A: 

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
Tim
I can't test with pcntl, server dosen't support it. Thanks all the same.
Chris