Skip to content

Instantly share code, notes, and snippets.

@marcelaraujo
Last active December 14, 2015 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcelaraujo/5038555 to your computer and use it in GitHub Desktop.
Save marcelaraujo/5038555 to your computer and use it in GitHub Desktop.
Check if a URL exists testing its header.
<?php
function checkUrl($url) {
if( !extension_loaded('curl')) {
trigger_error('The curl extension was not loaded.', E_USER_ERROR);
}
$status = preg_match('/^https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.\-?]*(\?\S+)?)?)?$/i', $url);
if( $status === false ) {
trigger_error('The preg_match returns a error code: ' . preg_last_error() , E_USER_ERROR);
} elseif( $status === 0 ) {
trigger_error('The url given is not valid.' , E_USER_ERROR);
}
ob_start();
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_VERBOSE, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5');
curl_exec($curl);
curl_close($curl);
$data = ob_get_clean();
preg_match("/HTTP\/1\.[1|0]\s(\d{3})/",$data,$matches);
return ( isset($matches[1]) && $matches[1] == 200 ) ? true : false;
}
// true
var_dump(checkUrl('http://www.google.com.br'));
// true
var_dump(checkUrl('http://www.globo.com'));
// true
var_dump(checkUrl('http://www.gradsch.ohio-state.edu/Depo/ETD_Tutorial/lesson2.pdf'));
// false
var_dump(checkUrl('http://www.globooooooooo.com'));
// false
var_dump(checkUrl('http://www.gradsch.ohio-state.edu/Depo/ETD_Tutorial/lesson2asdasd9a8s7d9as86d.pdf'));
@xeoncross
Copy link

I wonder how this compares to simply opening a socket and reading a couple bytes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment