Easy Create Email PHP Contact Form with Validations

First you create 2 files

1. contact.html
2. sendmail.php



Create file :- Contact.html

<form name="contactform1" method="post" action="sendmail.php">

    Name : <input type="text" name="txt_name" size="50">

    Email ID : <input type="text" name="txt_email" size="50">

    Message : <textarea name="txt_message" cols="10" rows="4"></textarea>

   <input type="submit" name="Email_Address" value="Submit"> 

<form>


Create file :- sendmail.php

<?php 
ob_start();


if(isset($_POST['Email_Address'])) {
     
    // EDIT THE 2 LINES BELOW AS REQUIRED
   $email_to = "phpweb1224@gmail.com"; // your email address
$email_subject = "Message from PHPWebLearn Contact Form"; // email subject line
     
     
    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br><br>";
        echo $error."<br><br>";
        echo "Please <a href='contact.html'>Click Here</a> and fix these errors.<br><br>";
        die();
    }
     
    // validation expected data exists
    if(!isset($_POST['txt_name']) ||
        !isset($_POST['txt_email']) ||
        !isset($_POST['txt_message'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');       
    }
     
    $txt_name = $_POST['txt_name']; // required
    $email_from = $_POST['txt_email']; // required
    $comments = $_POST['txt_message']; // required
     
    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
  }
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$txt_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.<br />';
  }  

  if(strlen($comments) <10) {
    $error_message .= 'The Comments you entered do not appear to be valid.<br />';
  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }
    $email_message = "Form details below.\n\n";
     
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:");
      return str_replace($bad,"",$string);
    }
     
    $email_message .= "Name: ".clean_string($txt_name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Message: ".clean_string($comments)."\n";
     
     
// create email headers
$headers = 'From: '.$txt_name."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $email_message, $headers);  
header('Location: contact.html');
}
die();
?>

First
Show Comments: OR