How to check validity of an URL

How to check validity of an URL.

1. Using Regex

if (ereg("^(http|https|ftp)\://[a-zA-Z0-9\.-]+\.[a-zA-Z0-9]{1,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\._\?\,\'/\\\+&%\$#\=~-])*$", $url)) {
echo 'URL Correct';
} else {
echo 'Bad URL';
}

This will validate URL with http, https and ftp schema.

2. Using fsockopen

$url = parse_url($url);
$conn = fsockopen($url['host'], 80);
if (!$conn) die('Cannot connect!');
fwrite($conn, "GET {$url['path']} HTTP/1.0\r\nHost: {$url['host']}\r\nConnection: close\r\n\r\n");
$header = fgets($conn);
if (preg_match('|HTTP/\S+\s+[2-3]\d\d|i', $header)) {
// HTTP response code 2xx - 3xx.
echo 'URL FOUND';
} else {
// Other
echo 'URL NOT FOUND';
}

3. Using cURL

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$http_code = (string)$info['http_code'];
if ($http_code{0} == 2 || $http_code{0} == 3 ) {
echo 'URL FOUND';
} else {
echo 'URL NOT FOUND';
}

This will check HTTP response code for the url.

Tagged with 
About sepedatua
I am nothing special, of this I am sure. I am a common man with common thoughts and I’ve led a common life. There are no monuments dedicated to me and my name will soon be forgotten, but I’ve loved another with all my heart and soul, and to me, this has always been enough.

Leave a Reply