title: How to check if a url exists with PHP and make it time out after a number of seconds
body: <p>I've used 2 different methods of checking the url so far:</p>
  
  <pre><code>$h = @get_headers($url);
  $status = array();
  preg_match('/HTTP\/.* ([0-9]+) .*/', $h[0] , $status);
  return ($status[1] == 200);
  </code></pre>
  
  <p>and</p>
  
  <pre><code>$file_headers = @get_headers($url);
  if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
  $exists = false;
  }
  else {
      $exists = true;
  }
  return $exists;
  </code></pre>
  
  <p>I'm just not sure how I can make these requests time out after a specified number of seconds. My script hangs for minutes, when a url doesn't exist, before it finally comes back as offline status. Any ideas?</p>
  
  <p>SOLUTION:</p>
  
  <p>Used Curl to set the timeout using the following code:</p>
  
  <pre><code>$curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_HEADER, true);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  curl_setopt($curl, CURLOPT_NOBODY, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  $data = curl_exec($curl);
  curl_close($curl);
  preg_match("/HTTP\/1\.[1|0]\s(\d{3})/",$data,$matches);
  return ($matches[1] == 200);
  </code></pre>