PHP Validate Email Address: Email Validator

When working with forms and interacting with your visitors, you may want to verify if your visitor entered an email address in the right field, and if it is valide or not.

Most of people who are new to php world, just verify if the text box of the email address is filled or not, without verifying the syntax of the email address...

Something like this they use:
if (isset($_POST['email'])) {
// do something
}


But when you want to develop a php website in the best way, taking care of all little details, you should think what happens when your user does make a mistake in the email address, writing something like this: his_email@gmailcom, or his_emailgmail.com or even he writes ssdfsff (like many people do), I'm sure you would like to inform him and ask him to correct his email address, you maybe also want to check if the domain name of his email address is valid, you can't accept an email like this: blahblah@dfsjhbhjjqsdqq.fdf .

So here is the php script I think you should use everytime you have a form with 'email address' input :
<?php
function validate_email($email) {

   //check for all the non-printable codes in the standard ASCII set,
   //including null bytes and newlines, and exit immediately if any are found.
   if (preg_match("/[\\000-\\037]/",$email)) {
      return false;
   }
   $pattern = "/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD";
   if(!preg_match($pattern, $email)){
      return false;
   }
   // Validate the domain exists with a DNS check
   // if the checks cannot be made (soft fail over to true)
   list($user,$domain) = explode('@',$email);
   if( function_exists('checkdnsrr') ) {
      if( !checkdnsrr($domain,"MX") ) { // Linux: PHP 4.3.0 and higher & Windows: PHP 5.3.0 and higher
         return false;
      }
   }
   else if( function_exists("getmxrr") ) {
      if ( !getmxrr($domain, $mxhosts) ) {
         return false;
      }
   }
   return true;
} // end function validate_email
?>
 


Now you can use this function with the email address you want to verify as parameter, and it will return you true if it valide and false if it is not.
This nice function will not know if an email exist really or not, it just verifies the syntax and the domain name, for example will not know that qsddsfqsdsdfqsdsqdsqd@gmail.com is not valide, but knows that qsqsdsq@dfsfsqdqsdqd.com is an invalid email address .

I hope this help you a lot.
Please leave comments or link to us if you think this is usefull :)

PHP Random code Generator

This is a very simple-to-use php function that help you generate random codes in very easy way, you will need this function to generate random passwords, confirmation links,...

So, this is it:
<?php
function createRandomPassword() {
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;
    while ($i <= 9) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return $pass;
}
?>


That's it!
There are many options you can play with, for example you can choose the characters to generate code from: $chars ="1234567890" will generate numeric code; $chars = "abcdefghijkmnopqrstuvwxyz023456789"; will generate alphanumeric codes. In fact the code will be generated randomly from the list of characters in $chars.

You can also change the lenght of the generated code by changing the value in "while ($i <= 9)", 9 here means you will get a code with 10 characters, as this counter (while) starts from 0 to 9. If you do "while ($i <= 7)" you will get 8 characters code.

This is the easiest and the best way to generate random code from php. I will always provide the best PHP scrips :)

If you like my blog, please give a link to us from your website, I will appreciate that :)

PHP Get browser Language

In php you can get the language of your visitor, this is very helpful if you have many versions of your website for different languages.

You can get the language of your visitor in this way:
<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
?>


This will give you the 2letter language code, ie: en for english and fr for french .

In fact $_SERVER['HTTP_ACCEPT_LANGUAGE'] will get all language the user prefer to use, in order. So substr() will give you the first choice, you can also get the second choice, the third ...

Having the language of your visitor will let you display custom page depending on his language, for example if someone's language is french, you will have $lang="fr" , then you can redirect him to www.yoursite.com/fr/ or yoursite.com/?lang=fr to show him your website in french, or show him things related to french language, whatever your website is about.

PHP $_REQUEST

You probably already know that you can get variable from a html form in php using $_GET and $_POST, you use $_GET if the html form is like: <form name="name" action="form.php" method="get"> and use $_POST if it is <form name="name" action="form.php" method="post">.

But what if you want your php to work for both post and get datas in the same time, to precess the form whatever it was in post method or get method, you will then think to use if conditions to check whether of two methods was used:

if (isset($_POST['var']))
// process data...
if (isset($_GET['var']))
// process data in the same way...

BUT there is a little and usefull solution: $_REQUEST, because $REQUEST can get any form field value, whatever it was GET or POST method, it does not care.

This means that $_REQUEST['var'] = $_POST['var'] if the form was in post method, and $_REQUEST['var'] = $_GET['var'] if the form was get. ('var' is the field name you want to get its value)
So now you will not care what method the form use :)

You can also use isset() with $_REQUEST, for example:
if (isset($_REQUEST['var'])) is the same than if ( isset($_POST['var']) or isset($_GET['var']) )

I hope this little tip will help you, we will provide best php tips, scripts as well as php tutorials.

PHP send mail SMTP authentification

this is a very complete php send mail script, with authentification ofcourse.
You can choose the smtp server, use your username and password, and can send a html email.

This script does not use php mail() function, it's all from scrach.





function authSendEmail($from, $namefrom, $to, $nameto, $subject, $message)
{

$smtpServer = "smtpout.europe.secureserver.net";
$port = "25";
$timeout = "30";
$username = "username@mailserver.com";
$password = "mypassword";
$localhost = "localhost"; //hosting server
$newLine = "\r\n";

$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 515);
if(empty($smtpConnect))
{
$output = "Failed to connect: $smtpResponse";
return false;
} else {
$logArray['connection'] = "Connected: $smtpResponse";
}

//Request Auth Login

fputs($smtpConnect,"AUTH LOGIN" . $newLine);

$smtpResponse = fgets($smtpConnect, 515);


//Send username

fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Send password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Say Hello to SMTP
fputs($smtpConnect, "HELO $localhost" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Email From
fputs($smtpConnect, "MAIL FROM: $from" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Email To
fputs($smtpConnect, "RCPT TO: $to" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//The Email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

//Construct Headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
//Add these two lines if you have any problem
//$headers .= "To: $nameto <$to>" . $newLine;

//$headers .= "From: $namefrom <$from>" . $newLine;


fputs($smtpConnect, "To: $nameto <$to>\nFrom: $namefrom <$from>\nSubject: $subject\n$headers\n\n$message\n.\n");
$smtpResponse = fgets($smtpConnect, 515);

// Say Bye to SMTP
fputs($smtpConnect, "QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);

return true;
}

?>

That's it, just copy this mail SMTP authentification function and change configuration variables values to your own (smtpserver, port, username, password, ...).