How to Create a Custom PHP Contact Form with Validation

PHP is a great scripting language that allows many dynamic functions in your site. You can create custom contact forms, form validation, and email responses using PHP. This article will explain the basics in creating an email form that validates the inputs, produces errors when inputs are typed incorrectly, and send an email to you when submitted.

This section of the code will validate the form inputs

Below is the code you will use to validate whether the inputs have valid data or not. This can be customized for different form field validations.

Note! You can paste the entire code directly in the body section of your webpage to get it working.

<?php 
if (isset($_REQUEST['submitted'])) {
// Initialize error array.
  $errors = array();
  // Check for a proper First name
  if (!empty($_REQUEST['firstname'])) {
  $firstname = $_REQUEST['firstname'];
  $pattern = "/^[a-zA-Z0-9\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
  if (preg_match($pattern,$firstname)){ $firstname = $_REQUEST['firstname'];}
  else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
  } else {$errors[] = 'You forgot to enter your First Name.';}
  
  // Check for a proper Last name
  if (!empty($_REQUEST['lastname'])) {
  $lastname = $_REQUEST['lastname'];
  $pattern = "/^[a-zA-Z0-9\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
  if (preg_match($pattern,$lastname)){ $lastname = $_REQUEST['lastname'];}
  else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
  } else {$errors[] = 'You forgot to enter your Last Name.';}
  
  //Check for a valid phone number
  if (!empty($_REQUEST['phone'])) {
  $phone = $_REQUEST['phone'];
  $pattern = "/^[0-9\_]{7,20}/";
  if (preg_match($pattern,$phone)){ $phone = $_REQUEST['phone'];}
  else{ $errors[] = 'Your Phone number can only be numbers.';}
  } else {$errors[] = 'You forgot to enter your Phone number.';}
  
  if (!empty($_REQUEST['redmapleacer']) || !empty($_REQUEST['chinesepistache']) || !empty($_REQUEST['raywoodash'])) {
  $check1 = $_REQUEST['redmapleacer'];
  if (empty($check1)){$check1 = 'Unchecked';}else{$check1 = 'Checked';}
  $check2 = $_REQUEST['chinesepistache'];
  if (empty($check2)){$check2 = 'Unchecked';}else{$check2 = 'Checked';}
  $check3 = $_REQUEST['raywoodash'];
  if (empty($check3)){$check3 = 'Unchecked';}else{$check3 = 'Checked';}
  } else {$errors[] = 'You forgot to enter your Phone number.';}
  }
  //End of validation

Sends the email if validation passes

The following code is what sends the email. The inputs must pass the previous validation in order for the email to send. You will need to replace the “to” email address with the email address you want to receive the email to.

if (isset($_REQUEST['submitted'])) {
  if (empty($errors)) { 
  $from = "From: Our Site!"; //Site name
  // Change this to your email address you want to form sent to
  $to = "[email protected]"; 
  $subject = "Admin - Our Site! Comment from " . $name . "";
  
  $message = "Message from " . $firstname . " " . $lastname . " 
  Phone: " . $phone . " 
  Red Maple Acer: " . $check1 ."
  Chinese Pistache: " . $check2 ."
  Raywood Ash: " . $check3 ."";
  mail($to,$subject,$message,$from);
  }
}
?>

Error Reporting Code

<?php 
  //Print Errors
  if (isset($_REQUEST['submitted'])) {
  // Print any error messages. 
  if (!empty($errors)) { 
  echo '<hr /><h3>The following occurred:</h3><ul>'; 
  // Print each error. 
  foreach ($errors as $msg) { echo '<li>'. $msg . '</li>';}
  echo '</ul><h3>Your mail could not be sent due to input errors.</h3><hr />';}
   else{echo '<hr /><h3 align="center">Your mail was sent. Thank you!</h3><hr /><p>Below is the message that you sent.</p>'; 
  echo "Message from " . $firstname . " " . $lastname . " 
Phone: ".$phone." 
";
  echo "
Red Maple Acer: " . $check3 . "";
  echo "
Chinese Pistache: " . $check2 . "";
  echo "
Raywood Ash: " . $check3 . "";
  }
  }
//End of errors array
  ?>

Prints the contact form

This is the form that will display for the visitor to fill out.

Contact us

 

Fill out the form below.

 

103 thoughts on “How to Create a Custom PHP Contact Form with Validation

  1. Excellent post! It is massively helpful to used my business site development. It works like a charm.

     

    Thanks.

    1. Where is the PHP code located on the server? Is an application required to run the PHP code?

      1. If you’re referring to the website files, then they will be in the PUBLIC_HTML folder by default. The web server recognizes PHP by default. If you’re not familiar with coding websites using PHP, then you should speak with an experienced website developer/designer.

    1. Stephanie, your question is unclear, but if you’re trying to obtain old code, you may need to contact your old web host.

  2. Hello. Can this code be adapted so that, instead of patterns, it checks the user input in a form field agains values stored in a mysql database?

    Thank you!

    1. Hello,

      Thanks for the question, but we’re not really sure what you’re asking. Are you referring to the answer response format being used for this page? If that is the case, you can find more information through using Joomla (the site uses Joomla to produce these pages). We can’t provide the specifics, but that is the main program being used to generate the answer and comment responses you see on the site.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  3. hi,

    i am confused about the fact that from which mailid the mail will get send.

    $from = "From: Our Site!"; //Site name

    will it work if i give any mailid without any permission problems
    1. Hello Lesio x,

      The FROM field is the string representing your website you’re sending from after an email is validated. If ANY id is given that does not give a permission problem, then the site name will work. It’s using the previous validation provided by the code at the beginning of the article.

      I hope that helps to answer your question! If you require further assistance, please let us know!

      Regards,
      Arnel C.

  4. I just read question or sharath. I am explaining you what he want to ask you. Actually his problem is like at the run time when he runs his HTML file, the cursor will have to transfer in mail.php file & performs all the operations (like sending mail) but instead of getting output he got whole code as output whatever he wrote in php file so why code is displayed & not the output.

    1. Hello,

      Is he using our code specifically? Or is he using a different set of code? If he’s using different code, then I suggest having the issue reviewed by a developer/programmer. Unfortunately, we cannot troubleshoot custom code. If you’re using our specific code, then please provide any error messages or an example of the output you’re seeing.

      If you have any further questions, please let us know.

      Kindest regards,
      Arnel C.

  5. Hello,

     

    i have some problems with your code (thank you anyway for it). I added some parameters to fit best with my site, but when i click to submit, i always have error with checkbox not checked (i want that ALL my checkbox must be checked to send the email) and also the first parameter “owner_name” always give me error ” You forgot to enter your Video Owner Name.”

    My php code (situated in another php file): 

    <?php

     

    if (isset($_REQUEST[‘submitted’])) {

    // Initialize error array.

     $errors = array();

     

     // Check for a proper Owner name

     if (!empty($_REQUEST[‘owner_name’])) {

     $owner_name = $_REQUEST[‘owner_name’];

     $pattern = “/^[a-zA-Z0-9\_]{2,20}/”;// This is a regular expression that checks if the name is valid characters

     if (preg_match($pattern,$owner_name)){ $owner_name = $_REQUEST[‘owner_name’];}

     else{ $errors[] = ‘Your Video Owner Name can only contain _, 1-9, A-Z or a-z 2-20 long.’;}

     } else {$errors[] = ‘You forgot to enter your Video Owner Name.’;}

     

     // Check for a proper Band name

     if (!empty($_REQUEST[‘band_name’])) {

     $band_name = $_REQUEST[‘band_name’];

     } else {$errors[] = ‘You forgot to enter your Band Name.’;}

     

     // Check for a proper Video Name

     if (!empty($_REQUEST[‘band_video’])) {

     $band_video = $_REQUEST[‘band_video’];

     } else {$errors[] = ‘You forgot to enter your Video Name.’;}

     

     // Check for a proper Band email

     if (!empty($_REQUEST[‘band_email’])) {

     $band_email = $_REQUEST[‘band_email’];

     if (!filter_var($band_email, FILTER_VALIDATE_EMAIL)) {

    $errors[] = ‘Your Band Email is wrong or you missed it.’;}

     }

     else{ $band_email = $_REQUEST[‘band_email’];}

     

     

     // Check for a proper Video Download Link

     if (!empty($_REQUEST[‘video_link’])) {

     $video_link = $_REQUEST[‘video_link’];

     } else {$errors[] = ‘You forgot to enter your Video Download Link.’;}

     

     // Check for a proper Video thnumbnail Link

     if (!empty($_REQUEST[‘thumbnail_link’])) {

     $thumbnail_link = $_REQUEST[‘thumbnail_link’];

     } else {$errors[] = ‘You forgot to enter your Thumbnail Download Link.’;}

     

     // Check for a proper Video Description

     if (!empty($_REQUEST[‘video_description’])) {

     $video_description = $_REQUEST[‘video_description’];

     } else {$errors[] = ‘You forgot to enter your Video Description.’;}

     

     

     

     if (!empty($_REQUEST[‘accept_tos’]) && !empty($_REQUEST[‘accept_rights’]) && !empty($_REQUEST[‘accept_publish’])) {

                    $check1 = $_REQUEST[‘accept_tos’];

                    if (empty($check1)){$check1 = ‘Unchecked’;}else{$check1 = ‘Checked’;}

                    $check2 = $_REQUEST[‘accept_rights’];

                    if (empty($check2)){$check2 = ‘Unchecked’;}else{$check2 = ‘Checked’;}

                    $check3 = $_REQUEST[‘accept_publish’];

                    if (empty($check3)){$check3 = ‘Unchecked’;}else{$check3 = ‘Checked’;}

                    } else {$errors[] = ‘You forgot to check all checkboxes.’;}

     }

     //End of validation 

     

     //email inviata

     if (isset($_REQUEST[‘submitted’])) {

                    if (empty($errors)) { 

                      $from = “From: eztv.altervista.org”; //Site name

                      // Change this to your email address you want to form sent to

                      $to = “[email protected]”; 

                      $subject = “PUBLISH VIDEO BY ” . $band_name . “”;

     

                      $message = “Owner name: ” . $owner_name . ” 

                      Band Name: ” . $band_name . ” 

                      Video Name: ” . $band_video .”

                      Band Email: ” . $band_email . “

                      Video Download Link: ” . $video_link . “

                      Thumbnail Link: ” . $thumbnail_link . “

                      Video Description: ” . $video_description . “”;

                      mail($to,$subject,$message,$from);

                    }

     }

    ?>

    <?php

    //Print Errors

     if (isset($_REQUEST[‘submitted’])) {

                    // Print any error messages. 

                    if (!empty($errors)) { 

                      echo ‘<hr /><h3>The following errors occurred:</h3><ul>’; 

                      // Print each error. 

                      foreach ($errors as $msg) { echo ‘<li>’. $msg . ‘</li>’;}

                      echo ‘</ul><h3>Your mail could not be sent due to input errors. Please go back and solve those errors.</h3><hr />’;}

                    else{echo ‘<hr /><h3 align=”center”>Your mail was sent. Thank you!</h3><hr />’;} 

     

     }

     

    ?>

    1. Hello Matteo,

      Have you tried to error trap the variable failing with something like var_dump($variable);

      Best Regards,
      TJ Edens

  6. Hi

    I am able to run this code, and shows that “Your mail was sent.Thank you!” but i’m confused where this mail is sending, here there is no fields regarding the same..kindly help me out

  7. Notice: Undefined variable: email2 inD:\XAMPP\htdocs\secure_email_code.phpon line 24

    Notice: Undefined variable: email2 inD:\XAMPP\htdocs\secure_email_code.phpon line 25

    Help please.

    1. Hello Szabolcs,

      From the error you have shown us, in the file secure_email_code.php you have stated a variable called $email2 and it has not been previously defined. Please remember that PHP works top down so you have to declare variables above where you use them.

      Best Regards,
      TJ Edens

  8. I’m confused. You say to put this all directly into the web page but is the comments you talk about making a .php file of some and .html of others. Please clearify.

     

    Tim

    1. I advise checking your SMTP settings to make sure everything is configured properly. Likewise, you can follow your mail logs for specific errors. Or, if you’re on a shared server I suggest you contact Live Support, so we can check the logs for you.

  9. I want to send a feedback form to my gmail from localhost server. it show the message to successfully send but i did not get the mail.

    *code removed by moderator*

    1. Hello Saran,

      You will want to contact your Support department to see what the email logs say about that particular email.

      Kindest Regards,
      Scott M

    2. Hello Rikhil,

      You will want to contact your Support department to see what the email logs say about that particular email. Since the function gave a successful result, they will check to see how the server handled the email to see if there was an error.

      Kindest Regards,
      Scott M

  10. Hellow, this the error message i get,

    Notice: Undefined variable: name in C:\wamp\www\kk\mail.php on line 45

    Warning: mail(): SMTP server response: 550 The address is not valid. in C:\wamp\www\kk\mail.php on line 52


    Your mail was sent. Thank you!

    My code is:

    <h2>Contact us</h2>
      <p>Fill out the form below.</p>
      <form action=”mail.php” method=”post”>
      <label>First Name: <br />
      <input name=”firstname” type=”text” value=”- Enter First Name -” /><br /></label>
      <label>Last Name: <br />
      <input name=”lastname” type=”text” value=”- Enter Last Name -” /><br /></label>
      <label>Phone Number: <br />
      <input name=”phone” type=”text” value=”- Enter Phone Number -” /><br /></label>
      <label>Red Maple Acer:
      <input name=”redmapleacer” type=”checkbox” value=”Red Maple Acer” /><br /></label>
      <label>Chinese Pistache:
      <input name=”chinesepistache” type=”checkbox” value=”Chinese Pistache” /><br /></label>
      <label>Raywood Ash:
      <input name=”raywoodash” type=”checkbox” value=”Raywood Ash” /><br /></label>
      <input name=”” type=”reset” value=”Reset Form” /><input name=”submitted” type=”submit” value=”Submit” />
      </form>

     

    mail.php is:

     

    <?php
    if (isset($_REQUEST[‘submitted’])) {
    // Initialize error array.
      $errors = array();
      // Check for a proper First name
      if (!empty($_REQUEST[‘firstname’])) {
      $firstname = $_REQUEST[‘firstname’];
      $pattern = “/^[a-zA-Z0-9\_]{2,20}/”;// This is a regular expression that checks if the name is valid characters
      if (preg_match($pattern,$firstname)){ $firstname = $_REQUEST[‘firstname’];}
      else{ $errors[] = ‘Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.’;}
      } else {$errors[] = ‘You forgot to enter your First Name.’;}
     
      // Check for a proper Last name
      if (!empty($_REQUEST[‘lastname’])) {
      $lastname = $_REQUEST[‘lastname’];
      $pattern = “/^[a-zA-Z0-9\_]{2,20}/”;// This is a regular expression that checks if the name is valid characters
      if (preg_match($pattern,$lastname)){ $lastname = $_REQUEST[‘lastname’];}
      else{ $errors[] = ‘Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.’;}
      } else {$errors[] = ‘You forgot to enter your Last Name.’;}
     
      //Check for a valid phone number
      if (!empty($_REQUEST[‘phone’])) {
      $phone = $_REQUEST[‘phone’];
      $pattern = “/^[0-9\_]{7,20}/”;
      if (preg_match($pattern,$phone)){ $phone = $_REQUEST[‘phone’];}
      else{ $errors[] = ‘Your Phone number can only be numbers.’;}
      } else {$errors[] = ‘You forgot to enter your Phone number.’;}
     
      if (!empty($_REQUEST[‘redmapleacer’]) || !empty($_REQUEST[‘chinesepistache’]) || !empty($_REQUEST[‘raywoodash’])) {
      $check1 = $_REQUEST[‘redmapleacer’];
      if (empty($check1)){$check1 = ‘Unchecked’;}else{$check1 = ‘Checked’;}
      $check2 = $_REQUEST[‘chinesepistache’];
      if (empty($check2)){$check2 = ‘Unchecked’;}else{$check2 = ‘Checked’;}
      $check3 = $_REQUEST[‘raywoodash’];
      if (empty($check3)){$check3 = ‘Unchecked’;}else{$check3 = ‘Checked’;}
      } else {$errors[] = ‘You forgot to enter your Phone number.’;}
      }
      //End of validation

      if (isset($_REQUEST[‘submitted’])) {
      if (empty($errors)) {
      $from = “[email protected]”; //Site name
      // Change this to your email address you want to form sent to
      $to = “[email protected]”;
      $subject = “Admin – Our Site! Comment from ” . $name . “go”;
     
      $message = “Message from ” . $firstname . ” ” . $lastname . ”
      Phone: ” . $phone . ”
      Red Maple Acer: ” . $check1 .”
      Chinese Pistache: ” . $check2 .”
      Raywood Ash: ” . $check3 .””;
      mail($to,$subject,$message,$from);
      }
    }
    ?>

    <?php
      //Print Errors
      if (isset($_REQUEST[‘submitted’])) {
      // Print any error messages.
      if (!empty($errors)) {
      echo ‘<hr /><h3>The following occurred:</h3><ul>’;
      // Print each error.
      foreach ($errors as $msg) { echo ‘<li>’. $msg . ‘</li>’;}
      echo ‘</ul><h3>Your mail could not be sent due to input errors.</h3><hr />’;}
       else{echo ‘<hr /><h3 align=”center”>Your mail was sent. Thank you!</h3><hr />’;

      }
      }
    //End of errors array
      ?>

    i dont under stand the error please help.

     

     

    1. Hello King,

      You will need to ensure your SMTP settings are correct for the email to process. WAMPs are not able to send emails unless you have set it up to be a mail server. This may be something you need to test live.

      Kindest Regards,
      Scott M

  11. Hi,

     

    I am looking for a tool which create single site and multile site setup in iss.

    This tool should create site, ftp, site directory and site app pool. 

    the tool should need to check, site user exists or not, site directory already exist or not , iis user for this particular exists or all validation.

    1. Hello Himanshu,

      Thank you for contacting us. Since we run all Linux servers instead of IIS, we do not provide any such solution.

      Thank you,
      John-Paul

    1. Hello freshar,

      Thank you for contacting us. We do not have any form available via zip folder link. Instead, the above guide provides the code as an example. You can paste the entire code directly in the body section of your webpage to get it working.

      Keep in mind you will have to customize the code to meet your specific needs.

      Thank you,
      John-Paul

  12. Please help me. I pasted in my website the script(work very well), but when i refresh the site, send another mail for us. What can i do with this problem!?

    1. Hello Gero,

      That happens because the ‘submitted’ state is still in effect. When the page is initially created, the state is not ‘submitted’. Once you submit the form, the browser has it set and does not it turn off. Contact Form pages were not made to be refreshed.

      Kindest Regards,
      Scott M

  13. Hi Arnel,

    I put the code in the html and while no errors were reported it failed to send the email. Do you know of any code that is 5.4 compatible?

    Thanks,

    Dan

  14. Hi Arnel,

    The HTML code is:

    <!doctype html>
    <html>
    <head>
    <meta charset=”utf-8″>
    <title>Untitled Document</title>
    </head>

    <body>
      <h2>Contact us</h2>
      <p>Fill out the form below.</p>
      <form action=”mail.php” method=”post”>
      <label>Name: <br />
      <input name=”name” type=”text” value=”” /><br /></label>
      <label>Email: <br />
      <input name=”email” type=”text” value=”” /><br /></label>
      <label>Message: <br />
      <input name=”message” type=”text” value=”” /><br /></label>
      <input name=”” type=”reset” value=”Reset Form” /><input name=”submitted” type=”submit” value=”Submit” />
      </form>
    </body>
    </html>

    It calls mail.php which is:

    <?php
      if (isset($_REQUEST[‘submitted’])) {
      if (empty($errors)) {
      $from = “From: Our Site!”; //Site name
      // Change this to your email address you want to form sent to
      $to = “[email protected]”;
      $subject = “Website Comment from ” . $name . “”;
        $message = “Message from ” . $name . ”  ” . $email . ”
      Message: ” . $message . ” ;
      mail($to,$subject,$message,$from);
      }
    }
    ?>

     

    Where do I put the error reporting code? As I said the above files work great on PHP 5.2.17 but not on 5.3.24.

    Dan

    1. Hello Dan,

      Our apologies as the person who originally created this post is no longer with us, so the code has not been updated. It would have to be reviewed and re-written at this point. The instructions in the code above indicate that the error reporting code belongs in the body of your website. I would place the code immediately after the body tag. This article will be flagged for further review for update purposes. Apologies if there is more confusion than clarity at this point. If you still have problems with its placement, then please let us know.

      I hope this helps to answer your question, please let us know if you require any further assistance.

      Regards,
      Arnel C.

  15. Where do I put it? Here is what is in my mail.php:

    <?php
      if (isset($_REQUEST[‘submitted’])) {
      if (empty($errors)) {
      $from = “From: Our Site!”; //Site name
      // Change this to your email address you want to form sent to
      $to = “email address removed”;
      $subject = “Website Comment from ” . $name . “”;
        $message = “Message from ” . $name . ”  ” . $email . ”
      Message: ” . $message . ” ;
      mail($to,$subject,$message,$from);
      }
    }
    ?>

    I tried putting int error_reporting ([ int $level ] ) in line two but Dreamweaver reported a syntax error.

    1. Hello Dan,

      The code would need to go into the body of your website , NOT in the MAIL.PHP application. I’m not familiar with your website code, but if you have an index page or main page that is used for the form , then the code should be appearing in that page. I hope that helps to answer your question! If you require further assistance, please let us know!

      Regards,
      Arnel C.

  16. No errors given but it will not send the email. I do have a server running 5.2 (which will be udgraded shortly against my will) that it works perfectly on. However the server I need it to run it on is running 5.3.24. The one it works on is running 5.2.17. I uploaded the exact same files to both. I am calling mail.php from the html file.

    1. Hello Dan,

      I would suggest trying the following php code to see if any errors are being suppressed. Other than that it should work the same. There may be some compatibility issues but the error reporting will let us know.

      Best Regards,
      TJ Edens

  17. How do I make this compatible with PHP 5.4? It will work on 5.2 but my server is 5.3 and will soon be 5.4.

    Thank you.

    1. Hello Dan,

      Are you receiving any errors while trying to use this script on PHP 5.4? Everything in here should be backwards compatible to PHP 5.2.

      Best Regards,
      TJ Edens

  18. Hello, i copy the same code that mention above and created seperate php file  callled mail.php and in my html file i used <form action=”mail.php” method=”post”>, but it goes to my mail.php page,  showing the code i have copied 

    please help to resolve tis error.

    1. Hello sharath,

      Thank you for contacting us today. We are happy to help, but will require some additional information since it is not clear what you are asking.

      Can you provide a link to the form, so we can test the error?

      Please include any additional information that will help us replicate the problem.

      Thank you,
      John-Paul

  19. Say I made a file for this called email.php. I have a website written in HTML & CSS and Javascript. How would I put this into the rest of the code so it shows op on the website?

    1. Hello Justice,

      Thank you for your question. I recommend that you paste the entire code directly in the body section of your webpage as described above. This will allow it to show up on the website.

      Alternately, you could navigate to the file PHP file directly, and it should run. Such as: https://example.com/email.php

      Thank you,
      John-Paul

  20. No, I have only tested from Google Drive. I’ve only picked up HTML and CSS in the last month, so I’m still relatively new to all of this and I don’t really know where to begin when it comes to hosting.

    1. Hello Kyle,

      I did some checking on Google Drive and did find the following statement on their page:

      “Google Drive does not support web resources that make use of server-side scripting languages like PHP.”

      So it looks like Drive is just for basic HTML and CSS, you would need to set up a WAMP environment on your local computer or get a free/cheap hosting plan in order to be able to test your php pages.

      Kindest Regards,
      Scott M

  21. I am completely new to PHP so please forgive me if this sounds stupid.

    I copied/pasted the php to its own file, put in my email address, and named it mail.php. In the HTML I set the action to mail.php. The problem is when I click submit, I get 404’d.

    Right now the HTML, CSS, PHP, and the image files are all in Google Drive instead of just being stored locally; they are not on a real website. I do this so that I can access the pages from any device and see how they react.

    Does anyone know why I am getting the 404 error?

    Thanks in advance.

    1. Hello Kyle,

      What you described sounds normal as far as the code goes. Have you tested it out on a webserver environment like WAMP? I am not familiar with testing on Google Drive, so I do not have any troubleshooting steps to take on that environment.

      Kindest Regards,
      Scott M

  22. Hi,

    I am having problems trying to require in email format. I cant seem to find a pattern that just allows a simple email? or is it more complex than that? I just need it for email format and required email feild, I dont need to validate actual email address. Thanks in advance for any help. And so far everything else is working just cant get this part!

     

    Kyle

    1. Hello Kyle,

      You can simply take the email address field and check to see that it has something in it. If you like, you can also check to ensure it has an @ symbol. This is not super detailed, but it gives an idea of whether they have entered an email address format in the field.

      Kindest Regards,
      Scott M

  23. This is the code i used

     

    <?php 

    if (isset($_POST[‘submitted’])) {

    // Initialize error array.

      $errors = array();

      // Check for a proper First name

      if (!empty($_POST[‘firstname’])) {

      $firstname = $_POST[‘firstname’];

      $pattern = “/^[a-zA-Z0-9\_]{2,20}/”;// This is a regular expression that checks if the name is valid characters

      if (preg_match($pattern,$firstname)){ $firstname = $_POST[‘firstname’];}

      else{ $errors[] = ‘Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.’;}

      } else {$errors[] = ‘You forgot to enter your First Name.’;}

      

      // Check for a proper Last name

      if (!empty($_POST[‘lastname’])) {

      $lastname = $_POST[‘lastname’];

      $pattern = “/^[a-zA-Z0-9\_]{2,20}/”;// This is a regular expression that checks if the name is valid characters

      if (preg_match($pattern,$lastname)){ $lastname = $_POST[‘lastname’];}

      else{ $errors[] = ‘Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.’;}

      } else {$errors[] = ‘You forgot to enter your Last Name.’;}

      

      //Check for a valid phone number

      if (!empty($_POST[‘phone’])) {

      $phone = $_POST[‘phone’];

      $pattern = “/^[0-9\_]{7,20}/”;

      if (preg_match($pattern,$phone)){ $phone = $_POST[‘phone’];}

      else{ $errors[] = ‘Your Phone number can only be numbers.’;}

      } else {$errors[] = ‘You forgot to enter your Phone number.’;}

      

      if (!empty($_POST[‘redmapleacer’]) || !empty($_POST[‘chinesepistache’]) || !empty($_POST[‘raywoodash’])) {

      $check1 = $_POST[‘redmapleacer’];

      if (empty($check1)){$check1 = ‘Unchecked’;}else{$check1 = ‘Checked’;}

      $check2 = $_POST[‘chinesepistache’];

      if (empty($check2)){$check2 = ‘Unchecked’;}else{$check2 = ‘Checked’;}

      $check3 = $_POST[‘raywoodash’];

      if (empty($check3)){$check3 = ‘Unchecked’;}else{$check3 = ‘Checked’;}

      } else {$errors[] = ‘You forgot to enter your Phone number.’;}

      }

     

      ?>

     

    1. Hello Brody,

      I’m sorry that you’re having problems with your contact form code. We unfortunately cannot provide support for your code. You will need to speak with a developer (if you were not the author of the code), to see where the problem is occurring. You should look at your error logs and see if anything has been generated. Apologies that we can’t directly with coding issues of this nature.

      Regards,
      Arnel C.

  24. Hello, when i used this code nothing seems to happen, it goes to my contact.php page, but nothing is displayed here is what i have for the html portion.

     

     

     

    <form action=”contact.php” method=”post”>

     

    <dl>

    <dt>First Name: <input type=”text” name=”firstname”></dt><br>

    <dt>Last Name: <input type=”text” name=”lastname”></dt><br>

    <dt>Phone Number: <input type=”text” name=”phone”></dt><br>

     

    </dl>

     

    <input name=”submitted” type=”submit”>

    </form>

  25. Warning: mail(): Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in C:\wamp\www\train\mail.php on line 54 .

    what is this error mean how could i rectify it..??

  26. <html>
    <body bgcolor=”#999900″>
    <center>
    <form method=”post”>
      <p>Owner name:
        <input type=”text” name=”user”>
        <br>
        <br>
    Enter Your Email ID :
    <input type=”text” name=”email”>
    <br>
    <br>

    Enter one Security Question :
    <input type=”<input type img style=”background-image:url(file:///C|/Users/Administrator/Documents/Unnamed Site 2/10342910_1426737800919777_3695156238055597333_n.jpg)”” name=”secu”>
    </p>
      <p>property size:
        <label>
        <select name=”select” accesskey=”3″ tabindex=”3″>
          <post>550</option>
          <post>800</option>
          <post>1000</option>
          <post>1200/option>
        <input type onKeyDown=””
       
        </select>
        </label>
        <br>
        <br>
       
       
        <input type=”submit” >
        <br>
        <br>
        </p>
    </form>
    ***************************************************************************
    <br>
    <marquee>
    <?php
    <method=”post” action=””>

    $a = $_POST[“user”];
    $d = $_POST[“email”];
    $e = $_POST[“secu”];

    $f = strlen($a);

    $g = “thirteen” ;

    if(“$f” >=10);

    <?
    {
    echo ” Plz Enter UserID , less then 10 character “; }

    { echo ” Security Answer is incorrect “; }
    else
    {
    echo ” Thank you for submission “; }
    ?>
    <br>
    </marquee>
    ***********************************************************************
    </body>
    </html>

    php script is not support plz help us for this page design my logic is enter the owner name, property size in list select valu goes to text box.

    1. Hello nilesh,

      We do not normally support custom code. What do you mean it is not supported? Are you getting an error message of some kind?

      Kindest Regards,
      Scott M

  27. Hello all,

    I really need help. I don’t know where to put my email, so when someone fills in the contact form, they click on the send button and it appears in my mailbox. So my question is; where in this script do I have to add something to receive messages in my mailbox? This script I use is also linked on a jquery. So I have a php form and a jquery. Please help me intelligent people! 😀         

    In my html I have add this:

    <form id=”form” action=”#”>

                <div class=”success_wrapper”>

                  <div class=”success”>Contact form submitted!<br>

                    <strong>We will be in touch soon.</strong> </div>

                </div>

                <fieldset>

                  <label class=”name”>

                    <input type=”text” value=”Name:”>

                    <br class=”clear”>

                    <span class=”error error-empty”>*This is not a valid name.</span><span class=”empty error-empty”>*This field is required.</span> </label>

                  <label class=”phone”>

                    <input type=”tel” value=”Telephone:”>

                    <br class=”clear”>

                    <span class=”error error-empty”>*This is not a valid phone number.</span><span class=”empty error-empty”>*This field is required.</span> </label>

                  <label class=”email”>

                    <input type=”text” value=”E-mail:”>

                    <br class=”clear”>

                    <span class=”error error-empty”>*This is not a valid email address.</span><span class=”empty error-empty”>*This field is required.</span> </label>

                  <label class=”message”>

                    <textarea>Message:</textarea>

                    <br class=”clear”>

                    <span class=”error”>*The message is too short.</span> <span class=”empty”>*This field is required.</span> </label>

                  <div class=”clear”></div>

                  <div class=”btns”> <a data-type=”reset” class=”btn”>clear</a><a data-type=”submit” class=”btn”>send</a>

                    <div class=”clear”></div>

                  </div>

                </fieldset>

              </form>

     

    The linked Jquery code is this:

    //forms

    ;(function($){

    $.fn.forms=function(o){

    return this.each(function(){

    var th=$(this)

    ,_=th.data(‘forms’)||{

    errorCl:’error’,

    emptyCl:’empty’,

    invalidCl:’invalid’,

    notRequiredCl:’notRequired’,

    successCl:’success’,

    successShow:’4000′,

    mailHandlerURL:’#’,

    ownerEmail:’#’,

    stripHTML:true,

    smtpMailServer:’localhost’,

    targets:’input,textarea’,

    controls:’a[data-type=reset],a[data-type=submit]’,

    validate:true,

    rx:{

    “.name”:{rx:/^[a-zA-Z’][a-zA-Z-‘ ]+[a-zA-Z’]?$/,target:’input’},

    “.state”:{rx:/^[a-zA-Z’][a-zA-Z-‘ ]+[a-zA-Z’]?$/,target:’input’},

    “.email”:{rx:/^((“[\w-\s]+”)|([\w-]+(?:\.[\w-]+)*)|(“[\w-\s]+”)([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,target:’input’},

    “.phone”:{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:’input’},

    “.fax”:{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:’input’},

    “.message”:{rx:/.{20}/,target:’textarea’}

    },

    preFu:function(){

    _.labels.each(function(){

    var label=$(this),

    inp=$(_.targets,this),

    defVal=inp.val(),

    trueVal=(function(){

    var tmp=inp.is(‘input’)?(tmp=label.html().match(/value=[‘”](.+?)[‘”].+/),!!tmp&&!!tmp[1]&&tmp[1]):inp.html()

    return defVal==”?defVal:tmp

    })()

    trueVal!=defVal

    &&inp.val(defVal=trueVal||defVal)

    label.data({defVal:defVal})

    inp

    .bind(‘focus’,function(){

    inp.val()==defVal

    &&(inp.val(”),_.hideEmptyFu(label),label.removeClass(_.invalidCl))

    })

    .bind(‘blur’,function(){

    _.validateFu(label)

    if(_.isEmpty(label))

    inp.val(defVal)

    ,_.hideErrorFu(label.removeClass(_.invalidCl))

    })

    .bind(‘keyup’,function(){

    label.hasClass(_.invalidCl)

    &&_.validateFu(label)

    })

    label.find(‘.’+_.errorCl+’,.’+_.emptyCl).css({display:’block’}).hide()

    })

    _.success=$(‘.’+_.successCl,_.form).hide()

    },

    isRequired:function(el){

    return !el.hasClass(_.notRequiredCl)

    },

    isValid:function(el){

    var ret=true

    $.each(_.rx,function(k,d){

    if(el.is(k))

    ret=d.rx.test(el.find(d.target).val())

    })

    return ret

    },

    isEmpty:function(el){

    var tmp

    return (tmp=el.find(_.targets).val())==”||tmp==el.data(‘defVal’)

    },

    validateFu:function(el){

    el.each(function(){

    var th=$(this)

    ,req=_.isRequired(th)

    ,empty=_.isEmpty(th)

    ,valid=_.isValid(th)

     

    if(empty&&req)

    _.showEmptyFu(th.addClass(_.invalidCl))

    else

    _.hideEmptyFu(th.removeClass(_.invalidCl))

     

    if(!empty)

    if(valid)

    _.hideErrorFu(th.removeClass(_.invalidCl))

    else

    _.showErrorFu(th.addClass(_.invalidCl))

    })

    },

    getValFromLabel:function(label){

    var val=$(‘input,textarea’,label).val()

    ,defVal=label.data(‘defVal’)

    return label.length?val==defVal?’nope’:val:’nope’

    }

    ,submitFu:function(){

    _.validateFu(_.labels)

    if(!_.form.has(‘.’+_.invalidCl).length)

    $.ajax({

    type: “POST”,

    url:_.mailHandlerURL,

    data:{

    name:_.getValFromLabel($(‘.name’,_.form)),

    email:_.getValFromLabel($(‘.email’,_.form)),

    phone:_.getValFromLabel($(‘.phone’,_.form)),

    fax:_.getValFromLabel($(‘.fax’,_.form)),

    state:_.getValFromLabel($(‘.state’,_.form)),

    message:_.getValFromLabel($(‘.message’,_.form)),

    owner_email:_.ownerEmail,

    stripHTML:_.stripHTML

    },

    success: function(){

    _.showFu()

    }

    })

    },

    showFu:function(){

    _.success.slideDown(function(){

    setTimeout(function(){

    _.success.slideUp()

    _.form.trigger(‘reset’)

    },_.successShow)

    })

    },

    controlsFu:function(){

    $(_.controls,_.form).each(function(){

    var th=$(this)

    th

    .bind(‘click’,function(){

    _.form.trigger(th.data(‘type’))

    return false

    })

    })

    },

    showErrorFu:function(label){

    label.find(‘.’+_.errorCl).slideDown()

    },

    hideErrorFu:function(label){

    label.find(‘.’+_.errorCl).slideUp()

    },

    showEmptyFu:function(label){

    label.find(‘.’+_.emptyCl).slideDown()

    _.hideErrorFu(label)

    },

    hideEmptyFu:function(label){

    label.find(‘.’+_.emptyCl).slideUp()

    },

    init:function(){

    _.form=_.me

    _.labels=$(‘label’,_.form)

     

    _.preFu()

     

    _.controlsFu()

     

    _.form

    .bind(‘submit’,function(){

    if(_.validate)

    _.submitFu()

    else

    _.form[0].submit()

    return false

    })

    .bind(‘reset’,function(){

    _.labels.removeClass(_.invalidCl)

    _.labels.each(function(){

    var th=$(this)

    _.hideErrorFu(th)

    _.hideEmptyFu(th)

    })

    })

    _.form.trigger(‘reset’)

    }

    }

    _.me||_.init(_.me=th.data({forms:_}))

    typeof o==’object’

    &&$.extend(_,o)

    })

    }

    })(jQuery)

    $(window).load(function(){

    $(‘#form’).forms({

    ownerEmail:’#’

    })

    })

    1. Hello.

      From skimming the code, ownerEmail:’#’, is what you would change to be your email but I would suggest contacting the developers of the script just to be sure.

      Best Regards,
      TJ Edens

  28. I am running this script on a localhost but the email is not being delivered even though the message says mail has been sent. Do I need to make changes to php.ini?

    1. Hello Bob,

      Thank you for your comment. PHP errors can be enabled to display and log errors using your local php.ini file.

      This can provide more details into what is happening.

      Also, be sure to check your spam box/email filter for the test emails.

      If you have any further questions, feel free to post them below.

      Thank you,
      John-Paul

  29. Hi,

    Advance thanks for your code. every think work fine. but I couldn’t receive the information to my email. I used one php file for entire code. If you could help Would be appriciaated.

    Kumar

    1. Hello Kumar,

      Thank you for your question. We are happy to help, but will need some additional information. Have you confirmed the email settings you entered are correct?

      Have you followed the above guide? Are you having any problems with a step?

      Have you reviewed the email logs to confirm if your script is communicating with the email server. (Live support can help you with that if you are on a shared server).

      Thank you,
      John-Paul

  30. Hello Anandita,

    Probably, you are writing the php code and the html code into the same xyz.html file.

    If you are using this instruction with the php script and html code in one file:

    <form action="" method="post">

    Then it is must that you will get the error which you have reported.

    I’ll suggest you to make a seperate php file and name it “mail.php”. And write the html code in seperate html file and use the following instruction:

    <form action="mail.php" method="post">

    Once you’ve done like this, you will not receive any errors. It is a tested method, as I experienced the same but when I added mail.php, everything becomes fine.

    I hope this will help you. Though my reply for your comment is too late, but I tried to help you and many others who is facing same error.

    Sincerely,

    Malik

  31. Thank you Arnel C.

    I really appreciate your prompt reply. I followed your suggestion and now all the emails are coming to inbox folder instead going to spam. BINGO..!! Thank you.

    I’d really like to share the part of php code which I changed.

    The original php code has:

    $from = "From: Our Site!"; //Site name

    Now, just change “From: Our Site!” with a valid email address like below:

    $from = "[email protected]"; //Valid email address

    By doing this, email will come to inbox with a valid reference email address and this will prevent email going into spam folder.

    Just thought to share, so that some one might get help by this. Any way brilliant work from admins.

    Thanks and Sincerely,

    Malik

  32. Hello,

    I will appreciate the admin on sharing this useful php based code. It really helped me a lot in designing my php contact form. 

    I have designed it and tested it successfully. Emails are coming to my email account but unfortunately in the SPAM folder with the tag (Unknown Sender).

    I’ll be grateful to you for your generous help to me.

    Thanks and Sincerely,

    Malik

    1. Hello Malik,

      Sorry for the problem with the form. It looks like the issue is a result of the “FROM” setting for the form. I would recommend that you set it to an email address instead of a website. If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  33. i want to make wesite  using php of my realtives they having a factory so which site i refer to get the knowlegde..i want like this only jst copy and paste so it is easy for me to create website.plz reply me soon plz

    1. Hello Ash,

      Thanks for the comment. Creating a website using only PHP will

        not

      be a copy and paste process no matter what tool you use. There are many applications out there that make it easy to create a website that uses primarily PHP, but I would suggest using WordPress. Our WordPress Education Channel provides a lot of information on how to install and start using the application.

      I hope this helps to answer your question, please let us know if you require any further assistance.

      Regards,
      Arnel C.

    1. Hello Hamman,

      Can you provide some more information on what you are wanting to create? Generally a good place to start coding simple websites is W3 Schools.

      Kindest Regards,
      TJ Edens

  34. I have the same issue as Anandita. I even cut and paste as is yet portions of the php script are getting printed to the page. Any idea what else could be causing this?

    Thanks.

  35.  the php runs off the server, the functionality should not be affected. The browser incompatibility will likely come in display inconsistencies. These are normally found in the CSS files/statements. 

  36. Thanks for the reply Scott.

    The websites and forms DISPLAY well in every browser,  But they seem to only actually send the message in Firefox and Chrome. Most messages in IE and some in Safari dont actually go through.  This is driving me nuts.

    1. As Scott stated, with it being PHP, the functionality of the form itself should not be affected as all code is executed within the browser. Are you using this same contact form that we have provided within this article?

  37. This article is very interesting. Thanks!

    I “inherited” the maintenance of some websites that use similar PHP functions for the contact forms, so this helps me understand what is going on. 

    BUT, I’m having a big problem with browser compatibility. Any idea what I should check on?  This is driving me nuts!

    1. Hello Lou,

      Since the php runs off the server, the functionality should not be affected. The browser incompatibility will likely come in display inconsistencies. These are normally found in the CSS files/statements in the page.

      Kindest Regards,
      Scott M

  38. What if you used radio buttons instead of checkboxes. How would the code look?

    I get the html part but the radio validation not sending the value of radio button clicked.

    Thanks

    1. Hello Betty,

      The checkbox is for when someone may select one or more of the options. Radio buttons force only one selection. Did you have code you wanted us to look at for errors? Replacing the checkboxes with radio buttons needs code modification not only on the form itself, but up where the validation is done.

      Kindest Regards,
      Scott M

  39. hi

    i will have to write this whole code in page or two page because it has three partition and php code is starting in partition one and ending in partition 2.

    1. Hello Ravi,

      You can put all three partitions in the same file. It was only split up on the article to show what purpose each partition serves.

      Kindest Regards,
      Scott M

    1. Hello Sak,

      Thank you for pointing that out. I found the error and corrected it. It has been tested and will not send an email if it is refreshed before the Submit button is pressed. A more updated version of this article should come out soon with a bit more polish.

      Kindest Regards,
      Scott M

  40. Hi.. Ive problem for make a contact us page. im using such your web for ‘post a comment’. its work and nothing error with that. but the comment cannot sent to the email. email cannot received the comment for page contact us. can help me to solve it?

    Thanks.

    Mira

    1. Hello Mira,

      If you are using just this article, then the email should send through fine. Are you one of our customers? Are you using additional SMTP settings to send your email through the server? If so, they will need to be correct in order to send out.

      Kindest Regards,
      Scott M

  41. i am using the above code for sending mail but getting error like this:

    The following occurred:

      ‘; // Print each error. echo ‘

    Your mail could not be sent due to input errors.


    ‘;} else{echo ‘


    Your mail was sent. Thank you!


    Below is the message that you sent.

    ‘; echo “Message from ” . $firstname . ” ” . $lastname . ”
    Phone: “.$phone.”
    “; echo “
    Red Maple Acer: ” . $check3 . “”; echo “
    Chinese Pistache: ” . $check2 . “”; echo “
    Raywood Ash: ” . $check3 . “”; } } //End of errors array ?>

     

    i don’t know why this error come when we click on submit button..pls help me soon..

    1. Hello Anandita,

      Be sure to check your code for syntax errors, particularly the placement of the quotes. Did you cut and paste it as is? It seems to work fine for me when doing that. Did you make any changes?

      Kindest Regards,
      Scott M

Was this article helpful? Join the conversation!

Server Madness Sale
Score Big with Savings up to 99% Off

X