Ever wished users entered valid Urls ?

Well why not force them ?

The problem


Usually web site owner want to extract all the possible information form their users and mor often want the information provided to be accurate!

Once one ofe those owners was nagging me becaus users where entering invalid urls like www./&%$#.com so I implemented a routine to validate if the Url exists

The solution


Fortunately Php has a pretty good networking support, as result you can create several network applications like, email clients, proxies, ftp clients, almost any sockets application

Step by step method :

We connect using fsockopen() function wicht basicly connects to the server and returns a file resource allowing us to use php file handling functions

We construct the HTTP header and ask for the default page

Now we get the server response.

The first line is the status code so we are only interested in that line and can close the connection

check the header for a "200 OK" message

The Code

function validUrl($host, $page =‘/’, $port=80) {
//server connection
$fp= fsockopen($host,$port,$errno, $errstr, 30);
if ($fp) {//ok, we are connected
//lets create the HTTP header to send
$header = "GET $page HTTP/1.0\r\n";
$header .= "Connection: Close\r\n\r\n";

//sending it
fwrite($fp, $header);

//getting server response (just one line)
$ret=fgets($fp);

//see if we got an 200 OK status
if (ereg(‘200 OK’,$ret)) {
fclose($fp);
return true;
}
fclose($fp);
}
return false;
}

if (validUrl(‘www.sapo.pt’)){
print ‘Valid’;
}else{
print ‘Invalid’;
}

Let me know what you think, leave a comment