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.

Source: http://crushedge.com/2008/12/02/how-to-check-validity-of-an-url/

Comments

Popular posts from this blog

The Importance Outdoors Activities For Children (cont.)

Control your heart and your feelings...