Ever wished users entered valid Urls ?
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 :
- Connect to server
We connect using fsockopen() function wicht basicly connects to the server and returns a file resource allowing us to use php file handling functions
- request a page
We construct the HTTP header and ask for the default page
- receiving the server response
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
- analyzing the server response
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’;
}