Jan 06 2010

Test if a remote url exists with PHP and CURL

Category: Php,Spiders & web botsGiulio Pons @ 10:13 am

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);
}
Share

Related posts:

  1. PHP code to check if remote mp3 exists
  2. PHP curl bot to update Facebook status
  3. How to change twitter status with php and curl without oAuth
  4. Tiny url encode and decode with PHP
  5. Copying remote files on your server with PHP

Tags: , , , , , ,

One Response to “Test if a remote url exists with PHP and CURL”

  1. Chris says:

    Awesome, just saved me a real headache. Top function worked perfectly, thanks!

Leave a Reply