How to Create a Contact Form using HTML5, CSS3 and PHP

[easy-social-share counters=0 style="button"]

Personally, I feel it is important to be aware of the positive effect HTML5 will provide on forms so the method they can function in many years to come. Realistically, we can’t implement just about all the brand new features today, but the truth is don’t need to be lagging behind the take a rest of the company whenever these functions lastly turn out to be easily held up.

Having had said that, this article will likely be focusing on the brand new HTML5 features that will be actually held up by almost all the main browsers, and that at the least employ attractive degradation for the browsers that will be still trying to play catch up.

Design

First thing, this will not be a Photoshop article. We have designed the take a look of the form, but then we’re going to be focusing on replicating it using the latest coding methods and then that makes it function in the correct way.

2

HTML5 Markup

Right now now we have a design to work toward, we’re going to form the structure of the contact form using HTML5. First of all, open it up a brand new PHP file folder and then save it as index.php. Right now, simply because we will need to using PHP to try to make the form function, you will require usage of a website server in order to try your code.Properly, you can setting up your personal machine as a server using Xampp; as an alternative, in case you have some online web hosting area, you can use that, but this technique usually means you will need to re-upload the data files when you would like to try these.

Doctype

Alright, right now we’ve became our blank PHP document, let’s get started with the appropriate doctype, which can be easier in HTML5 then last versions to say the least!

<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Contact Form</title>

</head>

<body>

</body>

</html>

Yes, that’s correct. There’s not terrible composition of characters and then numbers to be aware of for theHTML5 doctype. Simply; <!DOCTYPE HTML>. 

Simply to analyze, here’s the doctype forXHTML; <!DOCTYPE html PUBLIC“-//W3C//DTD XHTML 1.0 Strict//EN” “http ://www.simple .com/TR/xhtml1/DTD/xhtml1-strict.dtd”>.

I have the emotion now we have a clear winner now? I believe this sets the precedent for HTML5, as numerous of the brand new tags and then attributes represent a simple technique of doing things that useful to take double the quantity of code and a couple of lines of JavaScript .

Structure

The upcoming stage to code the simple structure of the web page, so that we will need to have a look at the design and also divide it into logical parts.

3
Then, we have now a header part, a articles part or a footer part. All of the very easy correct? Yes, however with HTML5, it’s actually simple. And then a lot more semantic as well.

<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Contact Form</title>

</head>

<body>

    <header class="body">

    </header>

 <section class="body">

    </section>

    <footer class="body">

    </footer>

</body>

</html>

That’s correct. Not any divs. HTML5 is introducing brand new tags that have already true meaning to say and then purpose, a lot more semantic than basically making use of divs in many different places. I’ve also given each one of these components a class of ‘body’ to show these are section of the major articles body and can be style of for this reason. You can actually of course do this with a div wrapper, however with just a few main body elements, it’s just like simple to assign classes in cases like this.

Form

It’s about time we got onto the Contact Form, correct? Of course, the markup for the form goes within the main  <section> tags.

<form>

    <label>Name</label>

    <input name="name" placeholder="Type Here">

    <label>Email</label>

    <input name="email" type="email" placeholder="Type Here">

    <label>Message</label>

    <textarea name="message" placeholder="Type Here"></textarea>

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

</form>

that’s the form markup, right now to explain a couple of things.

Input Tag

Maybe you have pointed out that the input tags work slightly in a different way to XHTML, exactly where they can be closed making use of the forward-slash character; <input/>. In HTML5, this tag has once again, also been simplified to just <input>.

Input Name

Almost all of the <input> tags also provide the name attribute declared. This comes in later on when ever we set up the PHP script that can manage the form data files.

Input Type

The type of element has seen a few biggest improvements in the transformation from XHTML to HTML5. The fact is that, many of the brand new <input> types can’t realistically be used as of the year but because of minimum help, but then it’s great to learn that they are going to help to make our jobs simpler and easier in years into the future.
Usually there are all the same, certain <input> different types that we can easily using, and also notice the best parts about today – having said that small these positive aspects may be. We have included type=”email” on this article, simply because there is not any negative aspect of making use of it – there is single benefits. It may perhaps not be anything at all unbelievable, but then it’s worthy of implementing, as any kind of browsers that don’t help this brand new input type, basically recognize it as type=”text”. And also on the i phone, this<input> type can cause a modified keyboards to look whenever the e-mail field is chosen, which include a lower space bar so the @ icon will take center target.

4

Placeholder Attribute

<input>elements are a different part of very important advancement in HTML5, allowing for developers to achieve the things that were previous to only possible with the use of a number of lines of JavaScript. The specific only one we’re using is the placeholder attribute, which can be responsibly very well held up in the most recent browser release. It permits you to select a value to a text field, which when chosen, disappears and also, in case no text has become entered, will certainly reappear once again when de-selected. I’ve used this plan for a very long time right now, but yet it’s always used a few big and bulky, ugly JavaScript code to allow it to be work.

11

CSS

After using have written the markup for the web page, that is the result…

5
Not so beautiful now is it? This is how you can actually using a few CSS to spruce options up a little bit or make it look and feel close to the natural design. First of all, let’s provide the form a much more similar look and feel by that makes it read top to bottom part and not just left to right.

label {

    display:block;

    margin-top:20px;

    letter-spacing:2px;

}

Providing the label components a property and then price of display:block; permits these to behave well just like a block level component, and thus pushing the written textboxes down onto the the next line. I’ve also applied a few extra self-explaining properties for spacing and then creative purposes.

8
The next, we will need to center the web page so the form, and then we’re going to style the <input> boxes, and after that we are going to basically start to see the web page enhance.

/* Centre the page */

.body {

    display:block;

    margin:0 auto;

    width:576px;

}

/* Centre the form within the page */

form {

    margin:0 auto;

    width:459px;

}

/* Style the text boxes */

input, textarea {

                width:439px;

                height:27px;

                background:#efefef;

                border:1px solid #dedede;

                padding:10px;

                margin-top:3px;

                font-size:0.9em;

                color:#3a3a3a;

}

textarea {

                height:213px;

                background:url(images/textarea-bg.jpg) right no-repeat #efefef;

}

Almost all of the above is amazingly quality CSS; making use of a width to the components with the .body class and also margin:0 auto; will center the web page, making the similar method centers the form within the web page.

The input or textarea components talk about most of the similar CSS values, then again there are actually a few properties that know the difference the main important message text box from the text areas. Observably the textarea needs a lot more height, but we’re also making use of a really simple background picture to this component. To do that we basically state the picture resource and also position it correctly by setting the many other background values to right and no-repeat.

7
Ok, at this moment we can easily insert the finish touches on to the text boxes with a little bit of CSS3.

input, textarea {

    width:439px;

    height:27px;

    background:#efefef;

    border:1px solid #dedede;

    padding:10px;

    margin-top:3px;

    font-size:0.9em;

    color:#3a3a3a;

    -moz-border-radius:5px;

    -webkit-border-radius:5px;

    border-radius:5px;

}

You will notice that we enjoy inserted 3 brand new lines to our CSS which is able to render rounded corners in just about all major browsers… except for of course for Internet Explorer 8 and then below. The standard border-radius property this will work in Opera, the –web kit prefix works best for Chrome and also Safari so the -moz prefix renders rounded corners in Firefox.

9
Just one final thing to addresses relating to the text boxes will be to select all of them a really understated :focus state as a way to provide a few visual feedback to the users actions. This, once more, couldn’t be easier.

input:focus, textarea:focus {

    border:1px solid #97d6eb;

}

You will see that there are just simply provided the  <input> and  <textarea> then elements a subtle blue border when they are currently selected.

10
Lastly, we’re going to set up our custom submit key. The submit key is an <input>component, even so we gave it its very own id=”submit” that allows you to overcome a few of the CSS we have actually installed on <input> components , since displayed below.

#submit {

    width:127px;

    height:38px;

    background:url(images/submit.jpg);

    text-indent:-9999px;

    border:none;

    margin-top:20px;

    cursor:pointer;

}

                #submit:hover {

                    opacity:.9;

                }

First of all, we allocate the appropriate width or height of the key, before setting it is background picture to the key we set up in the design. The text-indent:-9999px; line a little bit of technique to hide the real ‘Submit’ text from the key and then basically show the background picture.

Lastly, we allocate the key a:hover state, within which we’ve made use of a different little part of CSS3 in the form of the opacity real estate, which can be generally held up across the larger browsers, except for from… for sure, you’ve expected it.

12

form function with PHP

Very first important things 1st, we will need to visit again the HTML so that we can easily insert a great number of bits that will actually permit the form to communicating with the PHP script.

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

    <label>Name</label>

    <input name="name" placeholder="Type Here">

    <label>Email</label>

    <input name="email" type="email" placeholder="Type Here">

    <label>Message</label>

    <textarea name="message" placeholder="Type Here"></textarea>

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

</form>

So that what’s also been inserted? Have a look at the opening up tag. We’ve inserted two or three brand-new attributes; technique and then activity.

The method=”post” attribute will provide the PHP script with a way of extracting the values from the form, so that the script can then do what it really would like with those values. The action=”index.php” attribute basically talks about the area of the PHP script; in this instance, simply because it’s just a few lines of code, we’re going to insert it more than the form in our index.php file folder. And when the form is submitted, it will be able to go into index.php and then look for the script.

Take on one more look at the HTML above so you will find that every one of the form components have the name attribute. The PHP makes use of this attribute to extract the data files from each one of the form elements. Let’s look into how it does this…

<?php

    $name = $_POST['name'];

    $email = $_POST['email'];

    $message = $_POST['message'];

?>

If you’ve never used PHP before, it might look a bit confusing – but it’s actually really simple. The$_POST part is a built in PHP function which is used to collect data from a form that uses method=”post” like ours does. The part that immediately follows this function, ‘name’ will have to correspond to the name attribute from the form input; in the first instance, name=”name” !
For that reason, this will likely pickup what ever data files has become inserted into the name field – right now we require some thing to retail store that data files in. This is when variables become very important. For this reason, $name is the variable that we can use retail store the data files from the name field. You can after that repeat it for the e-mail and then message fields. Easy !
Right now, we’re leading to insert a little more variables that the form needs in order to function.

<?php

    $name = $_POST['name'];

    $email = $_POST['email'];

    $message = $_POST['message'];

    $from = 'From: Demo';

    $to = 'demo@demo.com';

    $subject = 'Hello';

?>

The new variables decide the desired destination of the e-mail, the topic field and also exactly where the e-mail has are coming from. Within the next stage, we can easily be storage of just about all the data files from the form from one variable that allows you to shorten things just a little.

<?php

    $name = $_POST['name'];

    $email = $_POST['email'];

    $message = $_POST['message'];

    $from = 'From: Demo';

    $to = 'demo@demo.com';

    $subject = 'Hello';



    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

?>

You will notice from the above snippet that we currently have taken the variables we announced previously that have right now collected all of them from one variable known as$body, that will be the actual articles of the e-mail.

It’s mainly time for you to using the mail( ) function to actually send the e-mail! But then 1st, we will need to tell you that this function will only be executed when ever the form is submitted but not each and every time the user loads index.php.

<?php

if ($_POST['submit']) {

    /* Anything that goes in here is only performed if the form is submitted */

}

?>

Basically, any code inside the above if statement will only be performed once the submit button has been pressed. Again, the [‘submit’] section will have to correspond to the name of the submit key in your form.

Right now you can easily go ahead and using themail( ) function.

<?php

if ($_POST['submit']) {

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

        echo '<p>Your message has been sent!</p>';

    } else {

        echo '<p>Something went wrong, go back and try again!</p>';

    }

}

?>

Themail( ) function is an integrated PHP function that basically works the assignment of sending the e-mail to the appropriate recipient. The above code makes use of an if statement, which simply states that when the mail function is finished right, and then say to the user the message has been sent; in case the mail function didn’t perform right, then simply inform the user that there have been an issue.

Right now, in case you test the form on your server you need to discover that it really works right ! The best method to make sure the form works it to try to upload it to an online server and also set the recipient email address because an e-mail managed on the similar server.

Notice that you can actually insert this script where ever you would like the approval message to appearance. As an example, if you would like the message to appearance above the form like it does indeed in the demo, then you definitely basically insert the PHP script direct above the form,NOT in individual PHP file folder.

Spam Prevention

Before we finish off, we’re going to look at a very simple method of spam prevention. To begin this process we must once again revisit the HTML and add in one more <input>element to our form. We’re going to insert this element just before the submit button.

<label>*What is 2+2? (Anti-spam)</label>

<input name="human" placeholder="Type Here">

Now back to the PHP, we need to use the POST method to extract whatever the user has entered into this field. Because we gave the element a name of “human”, we add the following line to our PHP; $human = $_POST’human’;. 

Just remember the PHP in case statement we useful to take care of functions only one time the form may have been submitted? Very well we’re going to require to slightly adjust that statement right now.

<?php

if ($_POST['submit'] && $human == '4') {

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

        echo '<p>Your message has been sent!</p>';

    } else {

        echo '<p>Something went wrong, go back and try again!</p>';

    }

}

?>

The statement at the moment needs that the value of‘human’ (the a reaction to the anti-spam questions) have to be ‘4’ in order that the mail function to be performed. Right now we will need to insert only one last little bit of code to let the user know when they have answers the anti-spam question the wrong way.

<?php

if ($_POST['submit'] && $human == '4') {

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

        echo '<p>Your message has been sent!</p>';

    } else {

        echo '<p>Something went wrong, go back and try again!</p>';

    }

} else if ($_POST['submit'] && $human != '4') {

    echo '<p>You answered the anti-spam question incorrectly!</p>';

}

?>

Now we have added onto our if statement with the use of else if, which in this case states that in case the form has become submitted so the answer to the anti-spam question was not ‘4’, then will not carry out the mail( ) function and then notify the user that their answer was incorrect.

And also that… is the fact that! The Last PHP code is to be found below and also back links to the trial so the CSS data file is to be found even more below. Thank you for reading. When you look at all of it – good quality hard work! And also permit me to know how you got on by leaving behind a comment below.

<?php

    $name = $_POST['name'];

    $email = $_POST['email'];

    $message = $_POST['message'];

    $from = 'From: Demo';

    $to = 'demo@demo.com';

    $subject = 'Hello';

    $human = $_POST['human'];

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if ($_POST['submit'] && $human == '4') {                                                         

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

                    echo '<p>Your message has been sent!</p>';

                } else {

                    echo '<p>Something went wrong, go back and try again!</p>';

                }

    } else if ($_POST['submit'] && $human != '4') {

                echo '<p>You answered the anti-spam question incorrectly!</p>';

    }

?>

Update

1 or 2 all people have wanted to know about helping to make the form work with required fields. Here’s the script you’d require in case the name and then email fields in my example were both needed fields…

if ($_POST['submit']) {

    if ($name != '' && $email != '') {

        if ($human == '4') {                                                 

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

                        echo '<p>Your message has been sent!</p>';

                    } else {

                        echo '<p>Something went wrong, go back and try again!</p>';

                    }

                } else if ($_POST['submit'] && $human != '4') {

                    echo '<p>You answered the anti-spam question incorrectly!</p>';

                }

    } else {

        echo '<p>You need to fill in all required fields!!</p>';

    }

}

And also here’s exactly how it would work !

Hope you all like this Tuts byCodiTuts.com, if yes then keep us supporting by sharing this post, Cheerful Coding smiley.

Submit a comment

Pin It on Pinterest