Click Here: Subscribe to me on Youtube!

Write your own webform using PHP with HTML

So you have a website and want to add a webform that sends you an email. You see fancy webforms on other sites and think 'I want a form like that for my site' - Well, you have come to the right place, because I'm gonna show you how to write your own form from scratch! (don't panic, its really not that hard)

There are many websites that will make a webform for you. They are ok, but very often will include loads of options you don't need or want. In this webform you are building it from the ground up, so only include what you actually need. My original 'made for me' webform was 53KB, but my new self-built one is only 7KB and it works just as good if not better.

Example form

This form design -like many others- uses HTML code to display the form and PHP as the magic that makes it all work, with CSS styling to make it look nice. It will be a PHP file and for convenience I will call it contact.php
I will try to explain each bit as I go along, so you can understand it and maybe modify the code to suit your needs. If you are more proficient at web design you may already know about many of the things I explain in detail. This page is designed with beginners in mind so please just skip over the bits you already know about.
To make it easier, I split it into three sections.

I am not a PHP or web-design expert, merely an enthusiastic amateur who likes to share what I learn. The information in this page has been used by me to create forms, so I know it works. If you spot an error please let me know.

My info will always be FREE. But if this helps you, please consider a donation to help keep the site going.

How to:

Styling the Form:

We start by creating the forms styling by using CSS (Cascading Style Sheets), this tells the web-page where to put things to make it look nice and not just a jumbled up mess on the page. In future web-design, when you learn more about styling, you will probably create the basic page first and then set about styling it afterwards. This CSS style code can be placed in an external file or incorperated into the page. In this instance we will keep it all in the same page. The CSS must be placed within the <head>...</head> section of the web-page.

<style type="text/css">
This tells the browser that the next commands are style commands

div.form {width:330px; margin-left:auto; margin-right:auto; overflow:auto}
This is the main div in which we are going to create the form. div.form tells the browser that this style should be applied to any div that is designated the 'form' class. The width of the form div will be 330 pixels, the margin-left and margin-right commands put the div in the centre of the page by creating automatically sized margins on either side. The overflow command stops any text from over shooting (or overflowing) from the div

div.formcell {width:330px; text-align:right; padding:5px 0 5px 0; overflow:auto;}
Inside the main form div, we will use seperate 'form cells' for each form element. The width is 330 pixels, the full width of the main div. The text is aligned to the right, so that the 'form label' text will appear next to the input box. We add 5px padding to the top and bottom of these 'form cells' just to make it look nicer. We could of used seperate padding-top and padding-bottom commands, but the shorthand version is neater. Shorthand code is: top right bottom left, and px is not required for any 0 amount. This shorthand can also be used with the margin command.

span.formlabel {display:block; float:left; width:135px; font-size:15px; color:#000;}
Inside the 'form cell' we need to seperate the input box from the name of that input (its 'form label'). We could put yet another div inside, but for a single word or two of text a div is overkill, so instead we use a 'span'. We float the block of spanned text to the left, so that the input box can sit to the right of it. Color is the font colour and is always spelt the American way.,, {float:right; width:180px; margin:0 0 0 5px;}
Here we tell the input boxes to sit to the right with a 5 pixel margin at the left, this is so the text label is slightly away from the input box

Tells the browser that this is the end of the CSS styling commands.

Creating the Form

Now we need to create the actual form. We use standard HTML (Hyper Text Markup Langauge) to create the form and use PHP (Personal Hypertext Preprocessor) to get the form to do what we want it to. All of the following code must be placed within the <body>...</body> section of the webpage

<?php $action=$_REQUEST['action']; if (==""){ ?>
This PHP command (along with a hidden form field further down) tells the form to do nothing until the Submit button is pressed. Without this command, the form will simply try to send as soon as the page is loaded when all the form fields are empty.

To create the forms fields, we will decide what fields we want and then we will make a div to put it all in. Each form field will be within its own div (we called these 'formcell' in the styling section) so that we can easily and neatly add a name or 'label' to it. All of the seperate field divs will be encompased by a main div which will keep everything together. For a basic form, we want a name field, email address field, email address confirmation, subject and message.

<form action="contact.php" method="POST">
Start the form code. "contact.php" is the file name of the contact form, it can be whatever you like, but the filename of the form and the filename here must be exactly the same or the form will not work properly.

<input type="hidden" name="action" value="submit"/>
This statement goes along with the PHP command above. If the form is not submitted then the "action" string remains empty and the form will wait until the submit button is pressed before doing anything. The user does not need to see this displayed within the form so we use the input type="hidden"

<div class="form">
This says we want to open a div. The 'class='command tells it that we want to use the styling called 'form' thats associated with a div (in this case div.form) from the style commands

<div class="formcell"><span class="formlabel">Name:</span><input type="text" name="Name" class="box"></div>
Open a 'formcell' styled div, Place the label of the form field inside a 'formlabel' span. Next we tell the form we want the user to enter some information. We use the 'input' command for this, and its type is text (because we want the user to enter text of course!). The 'name=' is very important, as later in the code this is what the PHP will use to identify the form field. You can name it whatever you like, but for simplisity -as this is the name field- we will call it name. The 'class=' command does exatly the same as the one in the above div only now it relates the style 'box' with the input command. Then close that div. This is now repeated -with different labels and names- for the email, confirmation and subject fields.

<div class="formcell"><span class="formlabel">E-mail:</span><input type="text" name="Email" class="box"></div>

<div class="formcell"><span class="formlabel">Confirm E-mail:</span><input type="text" name="Confirm" class="box"></div>

<div class="formcell"><span class="formlabel">Subject:</span><input type="text" name="Subject" class="box"></div>

<div class="formcell"><span class="formlabel">Message:</span><textarea name="Message" rows="4" class="box"></textarea></div>
This line is very similar to the 4 above, but as we expect more than two or three words of text we now use the 'textarea' command instead. 'rows=' simply tells the form how many lines (or rows) of text the textarea will hold. Basically this is the height of the textbox, more than 4 lines of text can be entered and it will simply scroll up. You can use as many rows as you like in your form, I use 4 as I think it looks proportional to the rest of the form.

To check its a human and not a spam-bot we can ask a question and have a drop down box to select the answer. It can be a very simple question, just don't phrase it as a typical question. For example, we use "Mary Had" instead of "What did Mary have?"

So, here is the code for the question:
<div class="formcell"><span class="formlabel">Mary had:</span><select name="Question" class="box">
As we do not want the user to type in anything, we use the 'select' statement to tell it we want a drop-down select field instead. Notice that we do not close the select statement yet, we first need to tell it what to put in the drop down list. To do this we use the 'option' statement.

<option value="an empty box">Select...</option>
The 'value=' of the option statement is what the HTML and PHP code will see, and the text outside of the option chevron is what the user will see. Normally both of these will be the same, but the first option is shown when the form is displayed, so we would let the user know they need to select an option and use a different word or phrase to let the code know nothing has been selected. Our question is 'mary had' and so if nothing is selected we tell the code that mary had an empty box. The next 5 options are selectable answers to the question.
<option value="a little goose">a little goose</option>

<option value="a little duck">a little duck</option>

<option value="a little lamb">a little lamb*</option>

<option value="a little cow">a little cow</option>

<option value="a little goat">a little goat</option>

Now we have entered all our options, we can end the select statment code and close the div.

You can use as many options as you like, to make it harder for spam-bot to guess the correct answer, just don't add TOO many and confuse the actual humans! You can see that I've added a star to the correct answer, just incase someone never heard of Mary and her Lambs before ;-) The star doesn't seem to cause any problems with the bots, so all good...

<div class="formcell"><input type="submit" value="Submit"/></div>
Put a submit button below the form

Close the main form div and end the form code.

Making it all work with PHP

Our form is looking good now, but that all it is, a good looking form... It doesn't actually do anything, and so we now have to add the magic PHP code to get it all working. We need to get the information from the form, then check it, and send it as an email.

This tells the browser that the next commands are PHP.

} else {
Remember the single line of PHP code we used to tell the form to do nothing until the submit button is pressed? This ELSE statement is linked to that. IF the submit button isn't pressed just do nothing, ELSE continue to process the data and send the form. Once the submit button is pressed it will activate the code below.

To make things easier, we will start off by grabbing the information from the form and store it as seperate strings of text. We could just call individual bits of information from the form as we want it, but its safer (and neater) just to grab it all at the start and store it as strings.

String names in PHP always start with a dollar sign ($) and can be anything you like, but to keep things simple we will give the strings the same names as the form fields. Here's how to do it:

$name = stripslashes($_POST['Name']);
The string called name equals the text entered into the form field called Name. The '$_POST' command pulls the text from the form and the 'stripslashes' statement does just that, it removes any slashes from the entered text. We repeat this to get the data from all of the form fields:
$email = stripslashes($_POST['Email']);

$confirm = stripslashes($_POST['Confirm']);

$subject = stripslashes($_POST['Subject']);

$message = stripslashes($_POST['Message']);

$question = stripslashes($_POST['Question']);

$answer = 'a little lamb';
The correct answer to the question we set in the form. We dont really need to convert the answer to a string, we could just enter it in the code as text later, but this just keeps things neat.

$date = date ("d.m.Y");
$time = date ("H.i");
These 2 commands get the current date and time so we can timestamp the email. This only grabs the time and date when the submit button is pressed, so we know its the exact time the form was sent.

Great, all the info we need is now converted into strings, now we just need to check it, format it and send it.

if (($name=="")||($email=="")||($confirm=="")||($subject=="")||($message=="")) {echo "<p><strong>ERROR: All fields are required! </strong>Please go back and check.</p>"; exit;}
This checks if any of the fields have been left blank, and if any are blank it will give an error message and tell the user to go back and check they have filled in everything. Note the double equals symbols in the IF statement. if you only use a single equals symbol (as in BASIC programming) it won't work.

if ($email != $confirm){echo "<p><strong>ERROR: Email address do not match! </strong>Please go back and check.</p>"; exit;}
If the email address string does not match (!=) the confirm email address string then give an error and tell user to go back and check.

if ($question != $answer){echo "<p><strong>ERROR: Mary didn't have $question! </strong>Please go back and check.</p>"; exit;}
Did the user enter the correct answer to the question? if not, we tell the user that Mary didn't have what they thought the answer was and to go back and check. There are more error and spam-bot checks we can add later, but for now we'll keep things basic.

$messagebody = "Name: $name \n\nE-Mail: $email \n\nSubject: $subject \n\nMessage: $message \n\n\nDatestamp: $date - $time";
Here we create a string called messagebody in which we create the format of the body of the email, this is how we want it to look when its sent. \n is the 'new-line' command and tells it to put the proceding text on the next line down. In the above statement we tell it we want the name first, then 2 new lines, their email address, then 2 more new lines, then the subject, and so on... Once the form is up and working, you can modify this to make it display how you like it. Just remember that you cannot use any HTML code here, it has to be plain text only.

$mailheader = "From: $email \r\n";
This sets up a string with the header of the email set-up in it, again in this instance we are keeping it simple and just using who sent the email.

mail(YOUR-EMAIL-ADDRESS, $subject, $messagebody, $mailheader) or die("Error!");
This actually sends the email. Put the email address you want the form to send to, in the place of YOUR-EMAIL ADDRESS above. If for any reason the form does not send it will show an error.

echo "<p><strong>Message Sent Successfully!</strong></p><p>We will get back to you soon.</p>";
When the mail is sent successfully, show the user a confirmation message.

Close the ELSE statement and end the PHP section.

Thats it! You should now have a nice looking form for your website... In the future I may update this page with some more in-depth spam-bot checks and other options, but this will get you up and running. - Good Luck, Norm.

Read the Disclaimer - Sitemap - Read the Privacy Policy
Design and Content is Copyright of N.Green ( ©2003 - 2017