If you have to test if a local file exists you will probably use the php file_exists function, but if you have to test a remote file, that is to say a remote url, than you can use CURL and get the headers returned by the http request. If you receive a 200 code, than it’s ok, else the url is not correct.
This function is included in the Mini Bots Class.
function url_exists($url) { $ch = @curl_init($url); @curl_setopt($ch, CURLOPT_HEADER, TRUE); @curl_setopt($ch, CURLOPT_NOBODY, TRUE); @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $status = array(); preg_match('/HTTP\/.* ([0-9]+) .*/', @curl_exec($ch) , $status); return ($status[1] == 200); }
If you you don’t have CURL lib istalled you can use the php get_headers function, it returns an array with the headers:
$url = 'http://www.example.com'; print_r(get_headers($url)); print_r(get_headers($url, 1));
If you apply the preg_match function to the first element of the array you will reach the same result:
function url_exists($url) { $h = get_headers($url); $status = array(); preg_match('/HTTP\/.* ([0-9]+) .*/', $h[0] , $status); return ($status[1] == 200); }
Awesome, just saved me a real headache. Top function worked perfectly, thanks!
Thank you , Saved me some time.
I’ve been searching for a solution like this for far too long;/
Thank You!!!!
and Best Regards!!