PHP Email Contact Form Tutorial

Email contact forms are a great way to add some visitor interaction to your website.

The best HTML can do for you in this area is a mailto email link. This isn’t very user friendly, especially if your visitor uses webmail, and not an email client app. It also makes you an easy target for spammers and their “bots”.

With a some HTML, a little PHP, and some CSS to make it appealing, you can craft an email form that gets site more feedback, less spam, and even make it look more professional.

Let’s get started

First, paste this HTML in the spot you want the form:

<form class="email" action="mailer.php" method="post">
<p>Name:</p>
<input type="text" name="name" />
<p>E-mail:</p>
<input type="text" name="email" />
<p>Subject:</p>
<input type="text" name="subject" />
<p>Message:</p>
<textarea name="message"></textarea></p>
<input class="send" type="submit" value="Send">
</form>

Now let’s add the PHP and make it do something. As you can see in the first line of HTML, it’s pointing a document called mailer.php. Let’s make that file. If you want to name it something else, or put it in a different directory/folder, just alter the address accordingly.

Create a new text file in your editor. Paste in this:

<?php
/* Set e-mail recipient */
$myemail = "YOUR EMAIL ADDRESS";

/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$subject = check_input($_POST['subject'], "Enter a subject");
$email = check_input($_POST['email']);
$message = check_input($_POST['message'], "Write your message");

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* Let's prepare the message for the e-mail */
$message = "

Name: $name
E-mail: $email
Subject: $subject

Message:
$message

";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>
<html>
<body>

<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>

</body>
</html>
<?php
exit();
}
?>

Save that as mailer.php.

If you’ve never messed with PHP, the looks can be pretty intimidating, but I’ll go over the basics of what all that means.

First you’ll see I’ve written your email address in all caps. Delete that and enter the email you’d like it to deliver to. It then checks to see if what the user has put in the form fits the criteria. If not, it asks them to properly add their name or email etc. Next, it prepares the inputted data to be sent to the email address you just provided at the top. Then, if the email is sent successfully, it redirects the visitor to another page on your website. You can just create a page saying the email was sent successfully and you’ll get back as soon as possible or something and put it’s URL there. The last part is what generates the error message if the data wasn’t entered correctly.

Your form is complete. It processes data input by a visitor and sends it to your inbox.

But it is a little ugly.

Doctor it up by adding some CSS

You’ll probably want to edit this to match your design, but here’s a little style to get you started:

form.email p {
font-size: 15px;
padding: 0 0 10px 0;
margin: 0;
}

form.email input, form.email textarea {
font-family: Arial;
font-size: 15px;
margin: 0 0 20px 0;
}

form.email input {
background: #f5f5f5;
padding: 5px;
border: 1px solid #bbb;
border-radius: 5px;
}

form.email textarea {
background: #f5f5f5;
padding: 5px;
border: 1px solid #bbb;
border-radius: 5px;
width: 400px;
height: 250px;
}

form.email input.send {
color: #fff;
background: #222;
border: #000;
padding: 10px 25px 10px 25px;
cursor: pointer;
}

In fact, for the Send button, you could use one of the background graphics I made specially for this type of thing.

You now have all the knowledge necessary to get started building your own PHP driven email contact form. If you’ve done so, and are still bringing in spam, but looking for a fix, you’re in luck. The very next post on Code Chirps will show you how to add a captcha!

Note:

PHP is a server-side language, so this form will only work on a web server unless you have MAMP or similar software running on your computer.

*Update: Professional installation

Due to a large amount of people commenting having problems getting this form running on their websites, I am now offering professional installation for just $49. This includes up to 5 custom fields and a custom graphic matching your current design for the “Send” button. For more information, contact me here.

If you enjoyed this article, why not share it with your friends? I’d appreciate it.

Get this delivered to your inbox!

It's quick, free, and painless.

Comments

  1. How to add a captcha! Oh man. I’m going to read that very carefully. Tried to do that a couple months ago and got SO confused. Google’s tutorial wasn’t very helpful.

  2. Sam says:

    Great post.. Very helpful for beginners as well as others..Thanks for sharing this..Keep posting such useful articles..Cheers!!

  3. John says:

    Ok maybe someone or maybe someone can not help me. But I can not get this darn php to work for nothing. I have deleted it from my server and copied and changed the email again. And then uploaded it to my server. Maybe someone can figure this out cause I can not figure it out. I have tried for 3 hours and now I am saying enough is enough till I get some help with this Thanks.

  4. Peter says:

    You are a star mate! Thanks!

  5. vickievik says:

    Thanks for sharing I have no idea of PHP, needed a PHP form script , but u provided the css decorating code too. U made my work easy…

    million thanks man
    GoodLuck

  6. You are the best. You deserve a hug and more.

    God bless you.

  7. SW Howard says:

    This is a great article and very helpful. Can you show us how to add a captcha to this code?

    Cheers!

  8. Jonatan says:

    You’re great!

  9. luzynel says:

    This is very helpful to me. Thanks a million sooo much! ^___^

  10. Bokkie says:

    Very handy indeed !
    Just wondering, I want to add an adres that people OPTIONAL can fill in.
    I can add the adres thing, but now it will always be checked and gives an error when not filled in..

    Any help with that?

    • Daniel says:

      Removing the lines of PHP that verify the address it should do the trick.

      delete:

      $email = check_input($_POST['email']);

      and:

      /* If e-mail is not valid show error message */
      if (!preg_match(“/([\w\-]+\@[\w\-]+\.[\w\-]+)/”, $email))
      {
      show_error(“E-mail address not valid”);
      }

      • Bokkie says:

        First of all thanks for the quick reply !
        But I think I didn’t make myself clear..

        I want to add an optional home-adres (and telephone number). The email, name and message are obligated, so that works fine as it is.

        This is what I tried : (translated in Dutch but it will be clear)
        In the PHP :
        $message = ”

        Naam : $naam
        E-mail : $email
        Adres : $adres
        Telefoonnummer : $telefoon

        Boodschap : $boodschap

        “;

        In the HTML :

        They don’t come in the mail though, I’m guessing that’s because they are not in the checklist on the PHP (on top), but when they ARE in the checklist they are no longer an option, but are obligated and that’s just what I don’t want.

        I hope this makes any sense, not a native english speaker.

  11. Moe says:

    Just wanted to say YES IT WORKED!! Thank you :)

  12. kay says:

    I have just joined 1and1, they are terrible. Dont have time to help their customers. I am new to php and I have got my form ready but is not working. 1n1 FAQ suggest i must change a few codes on formmail.pl which ive done.

    this is the big problem:

    I am using easyphp on windows, please help. A form like yours would be lovely lol

  13. Adam says:

    Hi Daniel,

    great post but im having some issues with the final step of linking the html to the php script. I am using mamp and have set up a folder in the mamp directory called ht docs the code is as follows:

    form class=”email” action=”Applications/MAMP/htdocs/mailer.php” method=”post”>

    When i press send this is what i get:

    The requested URL /Applications/MAMP/htdocs/mailer.php was not found on this server.

    any idea what im doing wrong?

    regards
    Adam

    • Daniel says:

      This just means the path in the link to the PHP file in the HTML file is incorrect. If both files are in the same directory, all you need is ‘mailer.php’. Otherwise write the path starting from the directory in which the file you’re linking from exists. If it is outside that directory, you put ../ to go up a directory.

      • Adam says:

        ok thank you it all works fine now apart from the messages do not send to the $myemail variable? As in i dont recieve any email once someone has filled out the form?

  14. Davide says:

    Great article!
    Short, clear and super useful!

    Thanks dude

  15. Tim says:

    Hi I did what you said above. But I get the error 500 code
    when I send:

    500 error

    What does it mean?

    Document not found — the requested file was not found on the server. Possibly because it was deleted, or never existed before. Often caused by misspellings of URLs.

    I am very not into programming scripts, just wonder what went wrong

    • Daniel says:

      500 error simple means the file wasn’t found, just like it says on the 500 error page. Check your links and make sure you have the correct names and paths in your linked documents.

      • Josh says:

        I got the same problem. I double and triple checked the path. here is a glimpse of my directory tree:

        _webber
        ├── contact-us.html
        ├── css
        │   └── …
        ├── images
        │   └── …
        ├── pageElements
        │   └── …
        ├── scripts
        │   └── mailer.php

        and here is the line in HTML:

        I don’t understand what the problem is. BTW, I do like how easy to follow your tutorial is and the way the form looks with the css, very clean. I made a few mods though ;)

        • josh says:

          I got this issue fixed by contacting support (I use cpanel on my hostgator account). It was a permissions issue. I am still waiting for a response as to what permissions are needed, but I thought I would post here in case others have similar problems.

  16. jose says:

    Thank you very much for this tutorial.
    I could make my contact form working with your help.

    I had a problem since 2 days and I couldn’t solve it before.

    Thanks again.

    Jose

  17. Thijs says:

    This is a great tutorial thanks alot! Please, can you tell me where to put the CSS code? In the mail.php or the HTML code?

    Greetings.

  18. Manza says:

    Hi there,

    I don’t know much about php, just some html, css and js…
    I tried this easy solution you kindly share with us but anytime I send the data (press the send button) I get redirect on the mailer.php page, which it’s what I guess it’s supposed to happend, but I display the html part:

    Please correct the following error:

    Hit the back button and try again

    I’m sure I’m making some very easy and stupid mistake, little help..? :)

  19. Leon says:

    Thanks Daniel for this awesome tutorial! I love it!

    1 question however, if you wanted to convert this to show email validation error messages on the same page (like above the text fields) instead of on another page, how would you do that?

    • Daniel says:

      Thanks man!

      That is certainly possible and something you see a lot, but that would require some much more complicated PHP than is used here and you’d have to start from the ground up rather than working off this form.

  20. Linda says:

    i got this error msg
    Notice: Undefined index: name in C:\wamp\www\mailer.php on line 14
    please help me to resolve it

  21. tolga says:

    not working!

    after activating send button, nothing happens
    it says it cant find the file but there it is

    just copy the address line or push f5!!!
    mailer.php in same file with index.php btw

    • John says:

      There might be a few problems that you might have.

      Do you have as it like on line 1 of the html?

      And on the php file make sure that is saved as mailer.php.
      Also check here to make sure that this line is also correct on the .php file.

      $email = check_input($_POST['email']);
      Make sure that the input($POST['email']; and the method=”post” in the html file. That has to be exactly like that for the php and the html file to work together.
      That is all I can come up with unless Daniel might have another suggestion.

    • Daniel says:

      It sounds as if your link is incorrect. Ensure that you include action=”mailer.php” at the beginning of your HTML form tag. It should fine it as long as you have the PHP file named correctly and in the same folder as your HTML file.

  22. Alex says:

    Thanks for the tutorial!

    What would the code (HTML and php) look like if I wanted to add a radio button to the form?

  23. Kayla says:

    Brilliant tutorial. Here I thought it’d be a nightmare trying to create something like this.

    I do have one, major issue though.
    I have it up and running. If a field is not valid it displays the proper error message. And when it’s perfect, it redirects them to the correct page. But it never actually sends the email. I tried both my yahoo and gmail on the off chance it’d be sent to spam. But I haven’t received any of the dummy emails I sent to myself. You wouldn’t have an idea why, would you?

  24. sam says:

    it doesnt seem to work. ive done everything, the page refreshes when you click submit but no emails get through.

  25. Ethan says:

    I have the same problem! It doesn’t seem to work. no emails get through.

  26. Empress says:

    Do you also need a mail server installed on your server to use an email contact form on your website?

  27. Mathew says:

    Thanks for this, dude. This is fantastic. By far the most straightforward tutorial on this that I’ve come across.

  28. John Pro says:

    I get this error message upon trying to send a test message.
    Warning: Cannot modify header information – headers already sent by (output started at /home/content/33/10547133/html/contact.php:6) in /home/content/33/10547133/html/contact.php on line 41
    I have only modified a few minor things on both html and php (ie names of forms and such) I did use DW spryboxes if that matters.

  29. Tariq Khan says:

    Respected admin! i m facing difficulty in mail connection.please check the code and fix the error. i will be very thankful to you for this kindness.
    if(isset($_POST["submit"])){
    $txtname = $_POST['txtname'];
    $txtPN = $_POST['txtPN'];
    $txtEmail = $_POST['txtEmail'];
    $txtAdd = $_POST['txtAdd'];
    $txtMarbleName = $_POST['txtMarbleName'];
    $txtSize = $_POST['txtSize'];
    $txtThickness = $_POST['txtThickness'];
    $txtAmount = $_POST['txtAmount'];
    $textAreaMessage = $_POST['textAreaMessage'];
    $headers = “From: mohmandms.eu5.org” . “\r\n” .
    “CC: somebodyelse@example.com“;

    $message.=’
    Name: “.$txtname.”
    Phone No: “.$txtPN.”
    Email: “.$txtEmail.”
    Address: “.$txtAdd.”
    Marble Name: “.$txtMarbleName.”
    Marble Size: “.$txtSize.”
    Thickness “.$txtThickness.”
    Amount: “.$txtAmount.”
    Message: “.$textAreaMessage;
    ini_set(‘localhost’,’25′);
    mail(‘khan_ge68@yahoo.com’,'Online Order Record’,$message,$headers);

    echo “alert(‘Information Send’)
    window.location.href=’onlineOrder.html’;”;

  30. Anna Beall says:

    I am a php beginner but everything seems to be correct but when I press submit it loads to the php file?

    • Daniel says:

      If PHP isn’t running on your server/computer it will simply load the file. You’ll need to put it on a server or install MAMP/WAMP.

  31. Remo says:

    My problem after trying the code is i get the error 405…
    Can I know what seems to be the problem?

  32. Portik Istvan says:

    Hi,

    I have a problem with your script.
    In my inbox, the email address is not display, just “Nobody”
    How to improve that?

    tanks

  33. Aaron says:

    Doesn’t work for me

    I’ve only changed $myemail field and uploaded to my server,
    script didn’t work

  34. Joshua says:

    Is there a way to change who the email is from? It appears it is pulling the server name. How would I change it to make it come from the sender’s email address?

    Thank you for the form!

  35. Lynn says:

    Hi there,
    I uploaded the code and it progresses to the page i want like it has sent however no emails have been received. How can i fix this?

    • Have you verified your email address in the PHP and also checked in your email’s spam filter?

      • Lynn says:

        I am also building a contact form that has a dropdown menu and the user can choose a topic from the dropdown to contact about. how can i adapt the code to allow the information from the drop down to be sent in the email as well as the other details?

        • Lynn says:

          This is my form Service Request

          Name

          Email Address

          Service

          Intruder Alarms
          CCTV Systems
          Access Control
          Fire Alarm Systems
          Analytics
          Door Entry
          Integrated Systems
          Monitoring

           

           

  36. Sande, John J. says:

    Hi Daniel,

    THANK YOU FOR THIS TUTORIAL. It has come really handy and worked perfectly on my site. However, one small issue. I don’t like the way {myError} is being displayed on a separate page, and have to ‘hit back’.

    Could you shed some light on:
    1. How to make the error message pop up on the same Contact Page/Email Form or displayed above the error point (e.g. Enter valid email) instead of loading a whole new page.
    2. Display all the errors (if available) at once instead of the current one-by-one.

    Much appreciate.
    John Sande (Nairobi, Kenya)

  37. knowhow says:

    Hi Daniel,
    Thanks a lot for this pretty tutorial. i copied your code and i write down my email address, but when i submit the form i got the thanks page that the mail is sent.
    But when ich ckeck my email i find nothing even in spam.

    I will be thankful if you make some suggestions.

    Best wishes.

    knowhow

  38. Naomi says:

    I changed the sum – just to be different…

    In the HTML:
    Message:

    What is:3 + 4 =
    (and yes this is in a table format)

    In the php:
    if (!preg_match(“|7|”, $captcha))
    {
    show_error(“You failed the security sum.”);
    }

    and now it no-longer works… any ideas as to why???

  39. Anna Lam says:

    i uploaded my contact form to my server, and the form does redirect me to the “thanks” page but I’m not getting any emails at all.

  40. Adam says:

    Hi Daniel can i post you my code because i still cant solve the problem?

    regards
    Adam

  41. Adam says:

    i think it is processing the PHP because it takes me to the thank you page. I dont at the moment im trying to get a contact form working to i can put my website online. Im really not sure whats wrong with it.

  42. Denise says:

    Awesome tutorial, thanks! I have this loaded on my server at http://www.mullerbrazil.com/myvaccine. The email sends, but instead of redirecting to the thank you page, I am getting the following error:

    Warning: Cannot modify header information – headers already sent by (output started at /home/content/91/9712091/html/myvaccine/mailer.php:12) in /home/content/91/9712091/html/myvaccine/mailer.php on line 44

    All I updated was the email address. Any ideas?

Speak Your Mind

*