Test if a remote url exists with PHP and CURL

If you have to test if a local file exists you will probably use the php file_exists function, but if…

Gennaio 6, 2010

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

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Comments on “Test if a remote url exists with PHP and CURL”

4 thoughts

  1. Chris ha detto:

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

  2. Woody ha detto:

    Thank you , Saved me some time.

  3. Virneto ha detto:

    I’ve been searching for a solution like this for far too long;/

    Thank You!!!!

    and Best Regards!!

Comments are closed

Recommended

How many times a web link has been shared on Twitter

Twitter share button and Facebook share button are the most used buttons to share links on Internet. You can read…

Ottobre 19, 2012

get MySpace events with a PHP function

Here is a function to read the concerts for a myspace band page. This code retrieves the “shows page” for…

Febbraio 21, 2011

PHP to get twitter infos and avatar

I’ve just updated the Mini Bot Php Class with an improved version of the twitterInfo function, here is the code…

Marzo 1, 2010

New version of Mini Bots PHP Class (v.1.4)

I’ve added three more bots to the Mini Bots Php Class, now the version number is 1.4 and it has…

Gennaio 20, 2010

PHP Web page to text function

I’ve found this nice small bot on the www.php.net site, thanks to the author of the script on the preg_replace…

Gennaio 16, 2010

Bot that retrieves url meta data and other infos

From a given url this function retrieves page title, meta description, keywords, favicon, and an array of 5 images to…

Gennaio 12, 2010