How to check the existence of URL in PHP?

Existence of an URL can be checked by checking the status code in the response header. The status code 200 is Standard response for successful HTTP requests and status code 404 means URL doesn’t exist.

Used Functions:

  • get_headers() Function: It fetches all the headers sent by the server in response to the HTTP request.
  • strpos() Function: This function is used to find the first occurrence of a string into another string.

Example 1: This example checks for the status code 200 in response header. If the status code is 200, it indicates URL exist otherwise not.



filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Initialize an URL to the variable
  
// Use get_headers() function
$headers = @get_headers($url);
  
// Use condition to check the existence of URL
if($headers && strpos( $headers[0], '200')) {
    $status = "URL Exist";
}
else {
    $status = "URL Doesn't Exist";
}
  
// Display result
echo($status);
  
?>

chevron_right


Output:

URL Exist

Example 2: This example checks for the status code 404 in response header. If the status code is 404, it indicates URL doesn’t exist otherwise URL exist.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Initialize an URL to the variable
  
// Use get_headers() function
$headers = @get_headers($url);
  
// Use condition to check the existence of URL
if($headers || strpos( $headers[0], '404')) {
    $status = "URL Doesn't Exist";
}
else {
    $status = "URL Exist";
}
  
// Display result
echo($status);
  
?>

chevron_right


Output:

URL Doesn't Exist

Example 3: This example uses curl_init() method to check the existence of an URL.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Initialize an URL to the variable
  
// Use curl_init() function to initialize a cURL session
$curl = curl_init($url);
  
// Use curl_setopt() to set an option for cURL transfer
curl_setopt($curl, CURLOPT_NOBODY, true);
  
// Use curl_exec() to perform cURL session
$result = curl_exec($curl);
  
if ($result !== false) {
      
    // Use curl_getinfo() to get information
    // regarding a specific transfer
    $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
    
    if ($statusCode == 404) {
        echo "URL Doesn't Exist";
    }
    else {
        echo "URL Exist";
    }
}
else {
    echo "URL Doesn't Exist";
}
   
?>

chevron_right


Output:

URL Doesn't Exist


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.