HTML5 Contact Form Using CSS & PHP

HTML5 Contact Form Using CSS & PHP


Some of my students were interested in learning how to create a simple contact form using HTML5, CSS and PHP to use within their current web composite projects. Although, this is not a requirement for the project and they have not covered forms and PHP in our program yet, I decided to create a simple “template” as an option for them to include in their projects.

In this post I will be walking you through how to use or repurpose the contact form for your own project. After explaining the HTML markup and CSS, I will be explaining how the PHP file works. It is important to know that the final form will only work if you have access to a web server (hosting). PHP will not function locally.

After customizing the form, you can simply copy the markup for the form and paste it into your own contact.html file for your project. Remember to relink the CSS style sheet and form.php file in your own HTML document.

*Note: This tutorial was intended for the student’s in our Graphic Design for Print & Web program. The instructions below are a simplified overview of an in-class lesson.

Download Code Demo

 

The Markup:

contact form html5

contact form html5

Open the contact.html document in Dreamweaver. I am using Coda 2, so my screenshots may look different from your setup. Copy everything within the <form> </form> tags and paste them into your own contact.html document.

<form action=”form.php” method=”post” enctype=”multipart/form-data”>

<h1 class=”title”>Contact</h1>

<label></label>
<input name=”name” required=”required” placeholder=”Your Name”>

<label></label>
<input name=”email” type=”email” required=”required” placeholder=”Your Email”>

<label></label>
<textarea name=”message” cols=”20″ rows=”5″ required=”required” placeholder=”Message”></textarea>

<input id=”cancel” name=”cancel” value=”Cancel” />

<input id=”submit” name=”submit” type=”submit” value=”Submit”>

</form>

The demo form that we have suggests two ways of adding titles to the form fields. The example above is using the “placeholder” attribute instead of placing the title of the form fields between the <label> </label> tags. The reason I did this is because the placeholder attribute within HTML5 allows us to assign a value to a text field, which gives the user a clear indication of what information needs to be entered in the text field. When the text field is selected by the user, the placeholder text disappears and, if nothing is entered by the user, the placeholder text will reappear when de-selected. Personally, I prefer using the placeholder attribute over the <label> tag because it makes for a cleaner and simpler looking form. This is just a matter of preference so I have included the <label> tag in the markup, just in case you want to use it and place your text field titles outside of the text field. If you would rather have your text field titles beside or above the text fields, then place your titles between the <label></label> tags and remove the placeholder attribute.

The other option that you may change in the markup is the Cancel and Submit button values. You may change these titles by changing the values for Cancel and Submit. For example, you can change these to value=”Reset” or value=”Send” if you like. You may also get rid of the Cancel input all-together if you would simply rather have the Submit option on its own.

The CSS:

form-css

Next, we will take a look at the CSS file. Open this document in Dreamweaver. It can be found within the css folder. I have placed comments for styling each element within the form. This portion is pretty straight-forward and you can change the styling for the H1 tags, inputs, textarea and submit buttons and hover states. If you would rather use an image for your submit buttons, I have included the styling (currently commented out) in the document. Make sure to create your submit images at  the exact width and height as indicated in your styling. This will ensure that your images will appear when previewing your form in the browser.

The PHP:

form php

form php

Now that we have our HTML markup and CSS ready to go, the last thing we need to do is set up the PHP file to send the inputted information to our email. Open the form.php file in Dreamweaver. The main thing we need to change is the $to variable. replace ‘youremail@gmail.com’ with your own email address. If you were to save the file and upload your web files to a server, the form would now send the information to your email. However, when you receive the email you will see that the subject of the email would say ‘Email Inquiry’ and the email would indicate that is from ‘YourWebsite.com’. To change this information, you can change the $from and $subject variables to what ever you wish.

*The first time you submit the form, the email may end up in your junk mail or spam box.

Once the user hits the submit button in the form, and everything goes well, they will get a message that says “Thank you for your email!”. If there is an error processing the form, the user will see an error message that says “Oops! An error occurred. Try sending your message again”. You can also change these messages if you wish within the if statement’s <p> tags.

Save. Upload. Test:

The final step is to save all of your files and correctly link them within your HTML so that the form works correctly. Save your HTML markup in your own contact.html document. Copy and paste the CSS into your own CSS stylesheet and update the styling of your form elements. Save your form.php file in the root of your website’s folder structure. Ensure that your HTML form markup is correctly linking to the form.php file’s location and your stylesheet is correctly linked as well.

*If you do not have hosting or access to a server, the form will not send the information that is submitted. However, you will at least have a styled HTML5 form that  you can now include within your composite project.

 

64 Comments

Add yours
  1. 3
    Juan

    Hi! I’ve been looking for a simple but effective tutorial and I think yours is perfect! I’m TOO newbie and I downloaded a html5 template with a contact form. I want to adapt it to this and maybe change the way of notifying that the email was sent correctly, but I still have to learn a lot…

    I still have one question. A php-form a sponsor of mine is using, sends me an email to my account as if these emails were sent by the clients themselves. I mean, in “from” field I can see the client’s email and by replying the email they receive my answer… It’s just easier to answer these way. Is it anyway possible to implement this here as well?

    Thanks again for your tutorial.

    Regards,
    Juan

  2. 6
    Amanda

    Very nice tutorial, thanks!
    One question. When I click on the “submit” button it takes me to another page that displays the “Thank you for sending this”-text. Is there any way to make that text appear on the same page as where the contact form is? Maybe under it or similar?

    Thank you.

    • 7
      Mark-Anthony

      Hi Amanda,

      You can do this by replacing the if/else statement with:

      if (mail ($to, $subject, $body, $from)) {
      echo ‘

      Thank you for your email!

      ‘;
      } else {
      echo ‘

      Oops! An error occurred. Try sending your message again.

      ‘;
      }

      • 8
        Amanda

        Thanks for your quick answer.

        Sorry, maybe I’m missing something, I still can’t get this to work.
        In the new code you sent me you’ve used ´ instead of ‘. Using ´ gives me an error, so I’ve replaced them with the ‘. I can see that you have removed the tags, other than that it’s the same code as the original, is it not? It is still sending me to another page when I press submit.

        Thanks!

  3. 12
    Steve

    Hi Mark,

    Very nice form. If you don’t mind, I have a question, as I am a newbie to PHP. How would I go about adding to the PHP file, a redirect to a specific page after a person clicks the submit button?

    Thank you.

    • 13
      Mark-Anthony

      Hi Steve,

      the current source files have a redirect in the form.php file. change the contact.html page to the page you wish to redirect to after the form is submitted. You can open the php file in any html editor you have.

  4. 14
    Vedant

    Hi mark, i was wondering why whenever i hit submit the server just downloads the form.php file. Im really new at this, and i need alittle bit of help.
    Thank you.

    • 15
      Mark-Anthony

      Hey,

      If your website is forcing your browser to download PHP files, Apache doesn’t recognise PHP as a valid file type. You might need to reconfigure httpd.conf so that it acknowledges PHP and its installation directory. Your files are being hosted on a server, correct? You won’t be able to test the form locally.

  5. 16
    Fran

    Hi Mark,
    As a first-timer to PHP I found this very useful. I just had a question though.. Whenever I submitted my form, the webpage would just go blank and not display one of the two messages, and the email did not come through to my inbox. Any ideas? Thanks.

  6. 20
    Nikki

    Mark:

    I appear to be having the same problem Fran experienced, and I can gladly tell you that I uploaded the files to the server where I would like it all to function.

    But like Fran said, form.php is blank, and zero e-mails are received in my inbox.

    Do you happen to have any suggestions? (Yes, I am on a PHP server…)

    Many thanks for your support!
    __
    Nikki

      • 22
        Jan

        Hello Mark! Thank you for a great tutorial. I’m experiencing the same problem as Nikki and Fran. I’m using your code on my demo website (www.tvojfarmar.sk) in Kontakt section. The result after submiting is just blank page. Any ideas? Thank you!

        • 23
          Mark-Anthony

          Hi Jan,

          I’m working on some new contact forms that should be free of any issues. I’m also going to create variations of the forms, ie: uploader, phone number, success message on same page and new page.

          For a quick fix, replace the code in the form.php with this code:

          < ?php if (isset($_POST['submit'])) { $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $from = 'From: mark-anthony.ca contact form tutorial'; $to = $email; $subject = 'HTML5 Contact Form Test'; $body = "From: $name\n E-Mail: $email\n Message:\n $message"; if (mail ($to, $subject, $body, $from)) { header ('Location: contact.html'); } else { echo '

          Oops! An error occurred. Try sending your message again.‘;
          }
          }

          ?>

          To make the form return to the home page or to your contact page, change the redirect URL, which is in line 16 of the code: header (‘Location: contact.html‘);

          If this is not a rush issue, I should have all the forms completed by next week and ready for download.

  7. 25
    David

    Hi, I would like to add an extra box for a telephone number but I’m struggling with the php side. I’m also having the same trouble as Amanda and Nemanja where the thank you text redirects to another page, in your examples above it seems all you’ve done is removed the p tags and shortened the text.

    • 26
      Mark-Anthony

      Hi David, to stop the redirect to a new page, change the URL in the form.php file to the same URL as your contact form.

      I’m currently working on upgrading these forms so you should be able to download and use two versions of the form. One that redirects to a new page and a version that has a “successfully sent!” message in a pop-up on the same page.

      To add a Telephone field, add this to your HTML form:


      And add this to line 4 of your form.php:

      $tel = $_POST[‘tel’];

      And replace this on line 10 of the form.php:

      $body = “From: $name\n E-Mail: $email\n Phone: $tel\n Message:\n $message”;

  8. 27
    Robin

    Hi Mark !
    The tutorial looks really great, but I just wanted to tell you that in my case the PHP pictures wasn’t displayed, and I had to go through the source code of the webpage to find the exact location of the JPG file and file have access to weird.
    This may not be a problem from your website, using Google Chrome from China has led to some unexpected Internet browsing issues that I never had met before…
    Congrats on the website !

  9. 29
    Ferg

    Hi Mark,
    Thanks for a great tutorial – it’s been a big help to me:-)..
    One issue I have encountered is that the field validation isn’t displaying as expected on Firefox (browser).
    Any suggestions on how to fix this?
    Many thanks,
    Ferg

  10. 33
    Kevin

    Hi Mark

    The php doesn’t works on Internet Explorer, it just gives a blank page like Fran, Nikki and Jan mentioned above, and no email coming thru the server to my email address.

    but when I tried on Chrome, it displays the echo message on Chrome, and the email coming thru my email address, so it works fine on Chrome.

    Could you let me know what’s the problem please?

    Thanks
    Kevin

  11. 42
    Jose Marzan

    Hi Mark-Anthony, thank you very much for this tutorial. i am a beginner web developer and has a lot of experience in desktop programming. i was looking for a tutorial til i found this. Cheers!

  12. 43
    daniel

    Hello. Great form. I was just wondering if there is a way you can show us how to implement a working anti spam field. Thank you.

    • 44
      Mark-Anthony

      I can certainly do that in my next version that I’m working on. However,
      Be patient with me. I’m occupied with client work at the moment but I’ll do my best to get something up soon. 🙂

  13. 45
    xaxe

    First give u the thanks Mark to this good tutorial. However i would like to know something else, is visible our e-mail inside of the file php for the “robots”? can anyone else see that e-mail if they see the code? The point is that i like a lot your example but iwould like to do it more “secure”, with some capchta or whatever else.

    • 48
      Mark-Anthony

      Hi Michael, Sorry for such a late reply. I’ve been really busy with work lately. Try adding a location like this at the end (I’ve made it bold):

      < ?php if (isset($_POST['submit'])) { $location = $_POST['location']; $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $email = $_POST['email']; $phone = $_POST['phone']; $service = $_POST['service']; $message = $_POST['message']; $from = 'From: Contact Form'; $to = 'youremail@gmail.com'; $subject = 'Email Inquiry'; $body = "Location: $location\n From: $firstname $lastname\n E-Mail: $email\n Phone: $phone\n Service: $service\n Message:\n $message"; if (mail ($to, $subject, $body, $from)) { header (‘Location: index.html’);
      } else {
      echo ‘

      Oops! An error occurred. Try sending your message again.

      ‘;
      }
      }

      ?>

    • 50
      Mark-Anthony

      Hi Keith, I’ve completed the forms but I haven’t had time to write out the tutorial. I began taking my Masters in Education earlier this year so my tutorials have slowed down lately. Sorry for the delay. I’ll try my best to get them done soon.

  14. 51
    jeremiah

    mark
    this contact form is a huge blessing to me. i will be using this in the contact section of my site. the one i was originally using was giving me a headache. im going to trashing that one and using this one! thank you so much

  15. 53
    denise

    I was looking for something smart and simple and now I’ve found it!
    One question though: the Cancel and Submit buttons – although they are both given the same height and width, when you look at them on screen the Cancel button is slightly wider than the Submit button I’m wondering if there is any way of fixing this? My pal, who I’m researching this for, is very pernickity and he’s bound to ask!!

    • 54
      Mark-Anthony

      There may be a border still on the cancel button. If so, add border: none; to the cancel button styling. The other solution may be to increase or decrease the margin or padding spacing by 1px. I’m also picking and not sure why I didn’t notice that. 😉

  16. 55
    Sarah

    Thanks for this tutorial! It has worked well except, I’m not receiving the emails.. I noticed someone else had mentioned that too. But I don’t receive any of the emails I’ve tested a few times. As well as I don’t really understand how to echo “thank you for your email” on the current page that the contact form is on. Could you maybe help me

    thank you!

      • 57
        Hugo

        Hiya Mark,

        I’ve got the same problem as Sarah above me. Everything works fine, exepct receiving the emails, neither in my junkbox.

        <?php
        if ($_POST['submit']} {
        if (mail ($to, $subject, $body, $from)) {
        echo 'Bedankt voor uw bericht $naam, wij proberen zo snel mogelijk te reageren.’;
        } else {
        echo ‘Oeps! Er ging iets fout, probeer het bericht opnieuw te versturen.’
        }
        }
        ?>

        Verzenden

        • 58
          Mark-Anthony

          Have you added more fields to the form? I’d need to see if you’ve updated or changed in the form elements so that I can help you further. By default, everything should be working if you simply enter your email in the send variable.

  17. 59
    Anthony

    I learnt a lot from your tutorial thank you so much
    After a bit more learning I was able get the contact form to work as expected I however have an issue when sending an email from the form

    When i view the sent email the reply address has the added ” @web2049c1.megawebservers.com” at the end of the email
    example domain.com@web2049c1.megawebservers.com I changed the email address but with the same result

    So it’s not any particular email address regardless of what email i use the added @web2049c1.megawebservers.com shows up

    Was really hoping you or any of your members could shed some light on this issue

    I’ve searched my entire web for any leads to the above mentioned link but to no avail

    any help would be greatly appreciated
    regards

+ Leave a Comment