Logo
Code Ranks ×

How to check the existence of URL in PHP?

11/03/2019  .   0 minutes, 57 seconds to read  .   Posted by Admin
#MVCArchitecture #Model,View,Controller #htmlemail

Different Methods to check URL Existence

We have two methods to check URL existence.

  1. Using get_headers functions

  2. Using PHP Curl

Using the get_headers function

According to the documentation, the get_headers function is used to fetch all headers sent by the server in response to an HTTP request(URL). We can use this function to read HTTP headers to check URL existence.

$url = "http://www.coderanks.com/";
$headers = @get_headers($url);
if(strpos($headers[0],'404') === false)
{
  echo "URL Exists";
}
else
{
  echo "URL Not Exists";
}

@-operator before get_headers function is used to suppress the error messages.

 

Using PHP Curl

Curl is a library that lets you make HTTP requests in PHP. We can use this to hit HTTP Url to verify it's existence.

$url = "http://www.coderanks.com";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
$result = curl_exec($curl);
if ($result !== false) 
{
  $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);  
  if ($status_code == 404) 
  {
    echo "URL Not Exists"
  }
  else
  {
     echo "URL Exists";
  } 
}
else
{
  echo "URL not Exists";
}

You can save these code scripts in two different files and verify it's working.