Bootstrap FreeKB - PHP - Determine if a URL exists
PHP - Determine if a URL exists

Updated:   |  PHP articles

The PHP @get_headers function can be used to determine if a URL does or does not exist.

<?php
  $file = "http://resources.freekb.net/css/default.css";
  $file_headers = @get_headers($file);
  foreach ($file_headers as $key => $value){
    print "\$file_headers[$key] == $value <br />";
  }
?>

 

Should return something like this. Notice that $file_headers[0] is HTTP/1.1 200 OK in this example. If the file is not found, $file_headers[0] would then be HTTP/1.1 404 Not Found.

$file_headers[0] == HTTP/1.1 200 OK
$file_headers[1] == server:nginx/1.23.3
$file_headers[2] == date: Sat Dec 25 2021 11:57:29 GMT
$file_headers[3] == content-type: image/png
$file_headers[4] == content-length: 20790
$file_headers[5] == last-modified: Sat Dec 25 2021 11:57:29 GMT
$file_headers[6] == etag: "abc123"
$file_headers[7] == accept-ranges: bytes
$file_headers[8] == connection: close

 

The following PHP can be used to determine if a URL exists. In this example, the following PHP will determine if http://resources.freekb.net/css/default.css exists.

<?php
  if ($file_headers[0] == 'HTTP/1.1 200 OK') {
    echo "$file exists";  }
  else {
    echo "$file does not exist";
  }
?>

 

Or like this.

<?php
  if ($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    echo "$file does not exist";
  }
  else {
    echo "$file exists";
  }
?>



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 5b65ce in the box below so that we can be sure you are a human.