Tag Archives: PHP

Email Validation using PHP

In one of my recent project I was required to validate email address in PHP. There are many ways to do this but I like following two approaches very much for which I created two different functions:

I created a function isEmail which will validate the email address and return true or false as per validation result.

First Approach: Using Filter functions (http://in.php.net/manual/en/function.filter-var.php)

This is quite simple and straightforward way using filter_var method and FILTER_VALIDATE_EMAIL constant which works on PHP 5.2+

Here is the function definition:
<?php
function isEmail_FirstApproach($strEmail)
{
if(filter_var($strEmail, FILTER_VALIDATE_EMAIL))
{
return true;
}
return false;
}
?>

Second Approach: Using Regular Expression (http://in3.php.net/manual/en/function.preg-match.php)
Regular expression is extremely powerful and quite confusing tool. So use it cautiously 🙂
Note: This function validates emails very well but quite not fully functional will all kind of emails. For e.g. Gmail gives option to add ‘+’ sign in emails which will fail with this functions and so on. Anyways you can easily enhance it 🙂

Here is the function definition:

<?php
function isEmail_SecondApproach($strEmail)
{
$strPattern = “/^([a-z])([a-z0-9._])+([a-z0-9])\@([a-z0-9])*([a-z])+(-[a-z])*([a-z0-9])*(\.([a-z0-9])*([a-z])+(-[a-z])*([a-z0-9])*)+$/i”;

if(preg_match($strPattern, $strEmail))
{
return true;
}
return false;
}
?>

Now simply call these functions to use it’s functionality as follows:
<?php
$email = “abc@example.com”;

if(isEmail_FirstApproach($email))
echo “Valid Email”;
else
echo “Invalid Email”;

if(isEmail_SecondApproach($email))
echo “Valid Email”;
else
echo “Invalid Email”;
?>

Note: Validation results can be different for different email addresses as filter validation is quite liberal than my Regex function.

Let me know if you find any issue with this or know any more efficient way to perform the same.


My First Experience with PHP Apache and MySQL

Finally I completed a website using PHP, MySQL and Apache web server after burning lots of candles and sleepless nights. I am normally an ASP programmer but always wanted to learn PHP from long time. So after giving much thought I started creating a website in PHP with back-end as MySQL during this vacation time. It took me two days to properly setup PHP, Apache and MySQL on windows XP machine. But after setting up I found that its quite easy, we just need to follow steps properly.

I completed this work in twenty days which i could have completed in around ten days if it was it ASP. Obviously PHP is new to me thats why it took time also I already have many previously built code by me in ASP ;-).

It was nice experience. Now I am getting more deeper into it and exploring more aspects of PHP, MySQL, Apache web server and associated technologies/tools.

and yes I’ll appreciate any guidance, suggestions or comments by you to improve my knowledge.