PHP – How to check if a URL exists or NOT? – Three Simple Solutions

I will present three relatively simple solutions, it is up to everyone to choose the solution they like best.

1’st php function using fopen (the simplest way):

function test_url($url) {
  $res = (($ftest = @fopen($url, 'r')) === false) ? false : @fclose($ftest);
  return ($res == TRUE);
}

2’nd php function, using fsockopen (not so simple) !

function test_url_2($url) {
  $addr=parse_url($url);
  $host=$addr['host'];
  $path = $addr['path'];

  $headtxt = ";

  if($sock=fsockopen($host,80, $errno, $errstr, 3)) {
    fputs($sock, "HEAD $path HTTP/1.0\r\nHost: $host\r\n\r\n");
    while(!feof($sock)){
      $headtxt .= fgets($sock);
    }
  }

  $pos1 = stripos($headtxt, "200 OK");
  return ($pos1 === false) ;
}

and 3’rd solutin using php CURL functions:

function test_url_3($url) {   
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_NOBODY, true);
  curl_exec($ch);
  $response_code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); 
  curl_close($ch);  
  return ($response_code ==  200);
}

All function return TRUE  if URL exists and FALSE if not !

byrev Written by:

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *