Validating emails with php

  1. Sanitizing and validating email syntax
    $email = $_POST['email']; //getting the posted email
    //sanitizing the email using FILTER_SANITIZE_EMAIL
    //removes all illegal e-mail characters from a string
    $email=filter_var($email, FILTER_SANITIZE_EMAIL);
    //validating the email using FILTER_VALIDATE_EMAIL
    //validates e-mail returning true if valid and false if invalid
    (filter_var($field, FILTER_VALIDATE_EMAIL)) ? TRUE : FALSE;
  2. Creating a function to validate and sanitize
    function check($email)  {
         $field=filter_var($field, FILTER_SANITIZE_EMAIL);
         return (filter_var($field, FILTER_VALIDATE_EMAIL)) ? TRUE : FALSE;
    }

    Usage:

    $email = $_POST['email'];
    if (check($email)==TRUE){
    //send email
    }else{
    echo "Invalid email!";
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">