Thursday, 18 August 2011

How to check Whether the URL valid or not in PHP


Whenever it is required to get some input url from user then the first things comes is checkwhether that url is working and valid or it is not working.

Here is a simple function which can be used to verify the liveness of the url.Just pass the url to this function and it will tell you whether the url is working and valid or invalid.In the function "check_url" we are going to open the given url with "fopen".If its opened then return true else return false.




<?php
//php function to check whether the url exists or not and validate it
function check_url($url)
{
$check = @fopen($url,"r"); // we are opening url with fopen
if($check)
 $status = true;
else
 $status = false;

return $status;
}
?>

Now we are going to use this function.you can pass the url from the GET or POST method to the function.Here we are going to specify it directly in the code.So we are asking our code to open the url http://www.techpdf.in with our function.



<?php
//$url = $_GET["url"]; // you can get the parameter from GET
$url = "http://www.techpdf.in";
if(check_url($url))
{
 echo "<div><a href=$url>$url</a> is a <b>valid</b> URL</div>";
}
else
{
 echo "<div><a href=$url>$url</a> is a <b>invalid</b> URL</div>";
}
?>


so after execution it will show the message as

http://www.techpdf.in is a valid URL.

No comments:

Post a Comment