How to validate an Email using PHP
In This Article, i will create a Form to collect User’s Email .
The User is Required to enter an Email into the Input box . Behind the back end, the PHP Script will validate whether the User has entered a correct Email format.
If the User entered a correct Format , the PHP Script will insert the User Email into MySQL Database.
Stepping through the code i will show you how to validate an Email using PHP.
Code for Validate an Email with PHP As Below
<?php // Include connection config file include ("C:/xampp/htdocs/dbconnection.php"); $userMail=""; $usermail_err =""; $emailBit = true; // Check whether Email Domain Exist function check_email_server($e){ $usermail_txt=""; $host = explode('@',$e); if (checkdnsrr($host[1].'.','MX')){ $emailBit = True; } else{ $usermail_txt = "Email Domain Not Valid."; $emailBit = False; } return $usermail_txt; } // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ if ($dbSuccess) { // Check If User Enter Emails $enterEmail=$_POST["tag_userMail"]; //check Whther the User enter Anything if(empty(trim($enterEmail))){ $usermail_err = "Please enter Your Email."; $emailBit = False; } // Check the Email Format is Correct if (!filter_var($enterEmail, FILTER_VALIDATE_EMAIL)) { $usermail_err = "Invalid email format"; $emailBit = False; } // If Email Format is Correct if (filter_var($enterEmail, FILTER_VALIDATE_EMAIL)){ // Check whether the email Domain Existed when Email Format is Correct $usermail_err =check_email_server($enterEmail); } if($emailBit) { // Prepare the SQL Statement and execute $email_SQL ='INSERT INTO emailstore (email)VALUES('.'"'.$enterEmail.'"'.')'; if ($dbConnectionStatus->query($email_SQL)) { echo " Email Inserted"; } } } } ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <style type="text/css"> body{ font: 14px sans-serif; } .wrapper{ width: 350px; padding: 20px; } </style> </head> <body> <div class="wrapper"> <p>Please Enter Your Email</p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <input type="text" name="tag_userMail" class="form-control" value="<?php echo $userMail; ?>"> <span class="help-block"><?php echo $usermail_err; ?></span> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Submit Your Email"> </div> </form> </div> </body> </html>
![validate email form](https://www.creatifwerks.com/wp-content/uploads/2020/08/validate-email-form.png)
Check Out How to Install Mamp or xampp with phpMyAdmin here