1

I have this code for checking urls:

function check_url($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    $headers = curl_getinfo($ch);
    curl_close($ch);
    return $headers['http_code'];
}

And my arrays:

$urls = array(1,2,3,"AAAA",4,5,6,7,8,9);

(For example AAAA takes 200ms and others takes 4s)

And this is my loop

foreach ($urls as $url) {
    check_url("http://www.example.com/" . $url);
}

Question is how can I set a timeout for each member? I mean, If checking member takes more than 2ms, jump to next member.

Edwin
  • 2,146
  • 20
  • 26
arazgholami
  • 15
  • 1
  • 4

1 Answers1

1

If you are using PHP version newer, than 5.2.3, you can use CURLOPT_TIMEOUT_MS curl option to do that.

So, in essence:

<?php
function check_url($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
    $data = curl_exec($ch);
    $headers = curl_getinfo($ch);
    curl_close($ch);
    return empty($headers['http_code']) ? 0 : $headers['http_code'];
}

$urls = array('http://www.google.com', 'http://www.tatawilkolak.pl');

foreach ($urls as $url) {
    echo check_url($url) . " ";
}
?>

If URL timeout'ed, returned HTTP code will be 0. In my code I have set 200ms as a timeout, but you can play with this number.

Tomasz Struczyński
  • 3,273
  • 23
  • 28