Jump to content


How to check if an external URL is valid (and/or get file size)


  • You cannot reply to this topic
No replies to this topic

#1 Shoel

    Administrator

  • Administrators
  • 125 posts

Posted 24 April 2010 - 11:49 AM

A fairly common thing people come across is the need to check whether a URL for an external file/resource, such as an XML document hosted by a 3rd party, is valid. I've seen various complicated ways of doing this, but the method I've found the quickest and easiest for simply checking whether it exists or not - is the following:

(This is intended for PHP 5)

<?php
/**
 * Check if an external URL is valid
 *
 * @param string $path
 * @return boolean
 */
function check_path($path){
  
  $headers = @get_headers($path);
  
  if (preg_match("/200/", $headers[0])){
    return true;
  }
  return false;
}
?>

In a nutshell it tries to fetch the HTTP headers for the given path/URL from the webserver hosting it, and if the response code is "200" (also known as "OK") - which indicate that the request has been received, understood, accepted and processed successfully. (The @ in front of the function call is PHP's error control operator - which tells it to ignore any errors/warnings it might generate.)

The same method can also be used to check content size (in bytes):

<?php
$headers = @get_headers($path, 1);

return $headers['Content-Length'];
?>

The second parameter to get_headers() simply tells it to parse the result and set the array key's to the corresponding header field names instead of numerical keys - which is a more reliable way of doing it. Note that even with this, the HTTP response code will always be key 0 in the array - for the sake of consistency. Thus we do not need to concern ourselves with the keys in the initial function described above.
Hi there! If you found this post useful, or used this information to help others, we would greatly appreciate a link back to our forum from your website/blog. Thanks! =)





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users