pTutorial

New way to learn PHP

PHP 5 URL validation

Email validation

In this section, we will learn how to validate a URL, whatever its email or website with the help of function and with the help of regular expression.

Html code

<html>
<body>
<form name="info" method= "post">
<input type="text" name="mail">
<input type="submit" name="Sub">
</form>
</html>
</body>

Email validation using function

<?php

if(isset($_POST['Sub']))
{
$email_id=@trim($_POST['mail']);
if($email_id=="" ) 
{
echo "error";
}
else
{
if (filter_var($email_id, FILTER_VALIDATE_EMAIL)) 
{
    echo "Entered email id is correct
"; echo "Your email id is: ".$email_id; } else { echo "You have entered wrong"; } } } ?>

PHP provides a filter_var function to filter the data, with a lot of filter flag, FILTER_VALIDATE_EMAIL filter flag is used to validate email. It returns filter data or return false if the filter fails.

Email validation using regular expression

<?php

if(isset($_POST['Sub']))
{
$web=@trim($_POST['web1']);
if($web=="" ) 
{
echo "You have not entered anything";
}
else
{

if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/",$web))
 {
  echo "You have entered wrong URL"; 
}
else
{
echo "Your URL is: ".$web;	
}

}
}

?>

You can also validate email with the help of regular expression, its a best method to validate email ID.

Website validation

To validate a website URL, use pre-defined PHP method or regular expression as shown below.

HTML code

<html>
<body>
<form name="info" method= "post">
<input type="text" name="web1">
<input type="submit" name="Sub">
</form>
</html>
</body>

PHP Validate URL

<?php

if(isset($_POST['Sub']))
{
$web=@trim($_POST['web1']);
if($web=="" ) 
{
echo "You have not entered any thing";
}
else
{

if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$web))
 {
  echo "You have entered wrong URL"; 
}
else
{
echo "Your URL is: ".$web;	
}

}
}

?>

You can validate URL with the help of regular expression, as shown above.

PHP IP Validation

<?php

if(isset($_POST['Sub']))
{
$ip=@trim($_POST['mail']);
if($ip=="" ) 
{
echo "You have not enterd any thing";
}
else
{
if (filter_var($ip, FILTER_VALIDATE_IP)) 
{
    echo "Entered ip is correct
"; echo "Your ip is: ".$ip; } else { echo "You have entered wrong IP"; } } } ?>

PHP provides a filter_var function to filter the data with a lot of filter flag, FILTER_VALIDATE_IP filter flag is used to validate IP. It return filter data or return false if the filter fails.


QUOTES OF THE DAY

Well-begun is half done.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER