How to validate URLs using PHP
Posted: Sun Nov 29, 2009 4:47 am
This script will allow you to validate a url (link). It can be used to validate an input value in a form or any other time you need to determine if a url is valid. If the url does not start with http:// it will be added. There is also a parameter (set to true in the script) for following redirects.
Code: Select all
<?php
$link = "google.com";
function http_file_status($url,$followRedirects = true) {
$url_parsed = @parse_url($url);
if (empty($url_parsed['scheme'])) $url_parsed = @parse_url('http://'.$url);
if (!is_array($url_parsed)) die('Processing Error - unable to parse url');
extract($url_parsed);
if (empty($port)) $port = 80;
if (empty($path)) $path = '/';
if (!empty($query)) $path .= '?'.$query;
$out = "HEAD $path HTTP/1.0\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n\r\n";
if (!$fp = @fsockopen($host, $port, $es, $en, 5)) return false;
fwrite($fp, $out);
while (!feof($fp)) {
$s = fgets($fp, 128);
if (($followRedirects) && (preg_match('/^Location:(.*)/i',$s,$matches))) {
fclose($fp);
return http_file_status(trim($matches[1]));
}
if (preg_match('@HTTP[/]1[.][01x][\s]{1,}([1-5][01][0-9])[\s].*$@',$s,$matches)) $status = $matches[1];
}
fclose($fp);
if (!empty($status)) return $status;
return false;
}
if (preg_match("(^(http://)?([-a-zA-Z0-9]+\.)+[A-Za-z]{2,4}([?\/]+[-&=\/\.\w]*)?$)",$link)) {
$url_parsed = @parse_url($link);
if (empty($url_parsed['scheme'])) $link = 'http://'.$link;
if (empty($url_parsed['path'])) $link = $link."/";
if (http_file_status($link) != "200") echo "Invalid link address"; else echo "Valid link address";
} else echo "Invalid url format";
?>