Email Validation Function

Written by @phuang 4 November 2022

Validating email submitted through a form is one of the most common tasks as a web developer. PHP provides an intuitive and easy way to validate email using two filters, FILTER_SANITIZE_EMAIL and FILTER_VALIDATE_EMAIL.

Code Snippet:

                                                
                                                <!-- this script is provided by https://www.phpfreecode.com coded by: Kerixa Inc. -->
<?php

if(empty($_POST)){
    
  if(isset($_SERVER['HTTP_REFERER'])){
      header('Location: ' . $_SERVER["HTTP_REFERER"] );
  }else{
      header('Location: https://'. $_SERVER['SERVER_NAME']);
  }
}else{


  if(isset($_POST['email'])){

    // Remove any illegal characters from email
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); 

    // Validate if it is a valid email based on RFC822 spec
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

      /* Passes validation, continue with your business logic */
      
    }else{
      echo "Invalid email format";
    }
  }else{
    echo "No email format found";
  }
}

?><a target='_blank' href='https://www.phpfreecode.com' style='font-size: 8pt; text-decoration: none'>Php Best Codes</a>                                                
                                            

Example:


About @phuang

Help desk analyst transitioning to a full-stack developer role. Hoping to learn and collaborate with everyone. Happy coding!

P

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: grkkid, Manaakividuinfo.com, karticksv, sava, tinatina
advertisement 2