MyBB Community Forums

Full Version: [tutorial] Creating a PHP & HTML form with validation
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Copyrighted Material, do not copy this tutorial as a whole, or in parts without permission of: rcpalace.

And no, a link back to one of my sites is not required when you use the code, that would be ridiculously dumb
.

Many people don't know how to do very simple tasks, such as contact forms or email forms. You end up going to some free form generator and making your site look very unprofessional.

What I'll teach You
This is going to be a step by step tutorial to build a basic yet effective form. We will use CSS (Cascading stylesheet), PHP (Hypertext Preprocessor), and HTML (Hypertext Markup Language). I will show you how to send data using Html and PHP from textboxes, to message boxes (textarea), to drop down menus and prepare you for anything you need that has to do with forms.

System Requirements

Make sure your server has PHP installed!
It wouldn't be fun to go through everything and end up not having PHP installed on the server. If you're not sure if it's installed contact your host. If you've built your server than be sure to have it installed with the below settings corrected:

Make sure your SMTP & "smtp_port" settings are correct in your php.ini file in order to be able to send emails through your server. If you're with a hosting company, you most likely don't have to worry about this step.

Make sure your server has Apache or other similar service installed. It is a necessity for your server to process webpages as-well as to understand HTML.

Let's Begin!
I'm not going to throw out some long un-understandable code for you to play with, I'm going to show you what each and every piece of code does.

I assume you have the html opening tag already done up to the body tag. So I'm not going to add those along with tutorial.

Create a new php file called "form.php", add the necessary html and follow the steps below:

We're going to begin with the php opening tag. A necessity for the parser to understand when php has started and when it ends.

<?php //php opening tag

 /*php closing tag */ ?>

Now, lets add some html, to add some html within php, you basically use the echo command. Within the echo command I will add the title of the form styled using css.

<?php
  echo "<div class=\"title\">Contact Form</div>\n";
?>

Notice the forward slashes between the quotes within the echo. That is used only when double quotes are used within the echo command so php understands that it is not the closing character and only string. In the end of the code I used this "\n", this basically tells php to make a line break within the sourcecode (not a visible break).
(Note: All the css will be given at the end of the tutorial.)

I assume you probably know how to start an html form. If you don't, you can do so by adding the following code:
<form method="post" name="contact" action="<!--url-of-what-processes-it-->">

</form>

You've probably noticed this "<!--url-of-what-processes-it-->", we will replace that in our code with itself or form.php.

Let's add the form opening tag (as shown above to our code):

echo "<form method=\"post\" name=\"contact\" action=\"form.php\">\n";

You should have this so far in form.php (excluding the html you've added):
<?php
  echo "<div class=\"title\">Contact Form</div>\n";
  echo "<form method=\"post\" name=\"contact\" action=\"form.php\">\n";
?>

Now let's add some input boxes. Make sure all input box names are relevant to what it is, otherwise, when it comes to field checks, you'll forget what you've named it.

<p><label for="name">Name:*<br /></label>
<input class="onebartext" name="name" type="text"  id="name" tabindex="2" value="<?php echo "$name"; ?>" /></p>

Now let's break it down. this "<p>" is the paragraph opening tag, I like it because it gives it a nice space cushion from other content. In the input code you'll notice class="onebartext" and "<?php echo "$name"; ?>" within the value. The class is used to define the style from the css file (will be shown at the end of the tut), the class name is onebartext. this "<?php echo "$name"; ?>" within the value is used to show what you entered after submit when an error return occurs. Be sure the echo "$name", is the name of the input box within the quotes. It's so they don't enter everything all over again. Now that you know how that works I'm going to insert it into our main code, yours should look like this so far:

<?php
  echo "<div class=\"title\">Contact Form</div>\n";
  echo "<form method=\"post\" name=\"contact\" action=\"form.php\">\n";
  echo "<p><label for=\"name\">Name:*<br /></label>\n";
  echo "<input class=\"onebartext\" name=\"name\" type=\"text\"  id=\"name\" tabindex=\"2\" value=\"$name\" /></p>\n";
echo "<br /><p><label for=\"email\">Email:*<br /></label>\n";
echo "<input class=\"onebartext\" name=\"email\" type=\"text\" id=\"email\" tabindex=\"2\" value=\"$email\" /></p>\n";
?>

Now it's time to add a drop-down menu. We will name this menu subject, and we will customize it so it will be added as the subject in the email.

<label for="subject">Subject:*<br /></label>
<select name="subject" class="form_box_s">
<option value="empty"></option>

<option value="[Contact Form]-Question">Question Regarding Your Services</option>
<option value="[Contact Form]-Other">Other (be specific in message)</option>
</select>

Since most of it is similar to the input box, I'm going to teach you about the options.

In "<option value="[Contact Form]-Other">Other (be specific in message)</option>" the value would be the subject that you will receive in the email, so be sure to make it understandable to when you receive it. this text "Other (be specific in message)" is what's visible to the visitor in the drop down menu, make sure it's relevant to the value. Then, you close the option by using "</option>". You've probably noticed this: "<option value="empty"></option>", This is my technique of checking if they selected a subject, once I make php understand it, I'll describe it more later in this tutorial. Now let's add it to our code. Your code should look like this now:

<?php
  echo "<div class=\"title\">Contact Form</div>\n";
  echo "<form method=\"post\" name=\"contact\" action=\"form.php\">\n";
  echo "<p><label for=\"name\">Name:*<br /></label>\n";
  echo "<input class=\"onebartext\" name=\"name\" type=\"text\"  id=\"name\" tabindex=\"2\" value=\"$name\" /></p>\n";
echo "<br /><p><label for=\"email\">Email:*<br /></label>\n";
echo "<input class=\"onebartext\" name=\"email\" type=\"text\" id=\"email\" tabindex=\"2\" value=\"$email\" /></p>\n";

echo "<label for=\"subject\">Subject:*<br /></label>\n";
echo "<select name=\"subject\" class=\"form_box_s\">\n";
echo "<option value=\"empty\"></option>\n";

echo "<option value=\"[Contact Form]-Question\">Question Regarding Your Services</option>\n";
echo "<option value=\"[Contact Form]-Other\">Other (be specific in message)</option>\n";
echo "</select>\n";
?>

Now let's add the textarea of where they can add their message.

<p><label for="message">Message:*<br />

<textarea class="textboxes" name="message" id="message" tabindex="3" rows="6"><?php echo "$message"; ?></textarea></label></p>

The only difference between this and the input boxes is the "textarea" instead of using "input". Now let's insert it in our code:

<?php
  echo "<div class=\"title\">Contact Form</div>\n";
  echo "<form method=\"post\" name=\"contact\" action=\"form.php\">\n";
  echo "<p><label for=\"name\">Name:*<br /></label>\n";
  echo "<input class=\"onebartext\" name=\"name\" type=\"text\"  id=\"name\" tabindex=\"2\" value=\"$name\" /></p>\n";
echo "<br /><p><label for=\"email\">Email:*<br /></label>\n";
echo "<input class=\"onebartext\" name=\"email\" type=\"text\" id=\"email\" tabindex=\"2\" value=\"$email\" /></p>\n";

echo "<label for=\"subject\">Subject:*<br /></label>\n";
echo "<select name=\"subject\" class=\"form_box_s\">\n";
echo "<option value=\"empty\"></option>\n";

echo "<option value=\"[Contact Form]-Question\">Question Regarding Your Services</option>\n";
echo "<option value=\"[Contact Form]-Other\">Other (be specific in message)</option>\n";
echo "</select>\n";

echo "<p><label for=\"message\">Message:*<br />\n";

echo "<textarea class=\"textboxes\" name=\"message\" id=\"message\" tabindex=\"3\" rows=\"6\">$message</textarea>\n";
echo "</label></p>\n";
?>

It's time to add the last parts to our form before we can begin the validation stage. Below is the code to add the submit button, the only difference between it and any input box is this: type="submit".

<input class="form_box_submit" type="submit" name="submit" value="Submit Your Message." tabindex="4" />
</form>

If you noticed this "</form>", it is used to end our form, don't forget to add it!
Here's how your code should look like now:

<?php
  echo "<div class=\"title\">Contact Form</div>\n";
  echo "<form method=\"post\" name=\"contact\" action=\"form.php\">\n";
  echo "<p><label for=\"name\">Name:*<br /></label>\n";
  echo "<input class=\"onebartext\" name=\"name\" type=\"text\"  id=\"name\" tabindex=\"2\" value=\"$name\" /></p>\n";
echo "<br /><p><label for=\"email\">Email:*<br /></label>\n";
echo "<input class=\"onebartext\" name=\"email\" type=\"text\" id=\"email\" tabindex=\"2\" value=\"$email\" /></p>\n";

echo "<label for=\"subject\">Subject:*<br /></label>\n";
echo "<select name=\"subject\" class=\"form_box_s\">\n";
echo "<option value=\"empty\"></option>\n";

echo "<option value=\"[Contact Form]-Question\">Question Regarding Your Services</option>\n";
echo "<option value=\"[Contact Form]-Other\">Other (be specific in message)</option>\n";
echo "</select>\n";

echo "<p><label for=\"message\">Message:*<br />\n";

echo "<textarea class=\"textboxes\" name=\"message\" id=\"message\" tabindex=\"3\" rows=\"6\">$message</textarea>\n";
echo "</label></p>\n";

echo "<input class=\"form_box_submit\" type=\"submit\" name=\"submit\" value=\"Submit Your Message.\" tabindex=\"4\" />\n";
echo "</form>\n";
?>

Now let's begin with the validation, I'm going to teach you some basic things, then I will place the code and give you the finalized unit so you don't spend most of your time reading instead of coding.

In order for php to know what form we're talking about, we need to tell it what submit button we're using. You use this code:

$_POST['submit'];

How about we make it an if statement?

if (isset($_POST['submit'])) {
//the code
}

Their, much better! "if", is telling php if, then. We have "if (isset($_POST['submit']))" isset is telling php if it was set or clicked on. $_POST['submit'] is basically grabbing the name of the input, or submit button. Then we begin the if by opening it {, then when we're done adding what will happen if the submit button was clicked, we close it using "}".

Phew! Now since that's explained, I will show you the code in hope you'll keep along. We're going to add the validation before the entire form so errors are up on top instead of on the bottom.

<?php
if (isset($_POST['submit'])) {
$name = htmlentities(trim($_POST['name']));
$message= htmlentities(trim($_POST['message']));
$email = trim($_POST['name']);
$subject = ($_POST['subject']);


 if (!$name) {
  echo '<div class="errors">';
  echo "Please enter your name!";
  echo '</div>';
 }

 elseif (!$email) {
  echo '<div class="errors">';
  echo "Please enter your email!";
  echo '</div>';
 }

 elseif ($subject=="empty") {
  echo '<div class="errors">';
  echo "Please select a subject!";
  echo '</div>';
 }

 elseif (!$message) {
  echo '<div class="errors">';
  echo "Please enter a message!";
  echo '</div>';
 }

 else {
 mail('[email protected]', "$subject >> $name", $message, "From: $email");
 echo '<div class="complete">';
 echo "Your message has been sent! &mdash; We will reply as soon as we get to your message.";
 echo '</div>';
 }
}
?>

Be sure to change "[email protected]" to your email. Don't say it, no, don't capitalize all the letters in your email, I just did it so it is more visible. Before I merge the code above into the code we worked on previously, you need to add this into your html that you made. The one not shown in the tutorial, the html opening tag, head, etc. Between the head tags in your html, add this for the css:

<link href="style_form.css" rel="stylesheet" type="text/css" />

Then download the css file from here:
[attachment=11070]

After you've downloaded it, extract it and add it in the same directory form.php is.

Here's the final code of what you should have:

<?php
if (isset($_POST['submit'])) {
$name = htmlentities(trim($_POST['name']));
$message = htmlentities(trim($_POST['message']));
$email = trim($_POST['name']);
$subject = ($_POST['subject']);


 if (!$name) {
  echo '<div class="errors">';
  echo "Please enter your name!";
  echo '</div>';
 }

 elseif (!$email) {
  echo '<div class="errors">';
  echo "Please enter your email!";
  echo '</div>';
 }

 elseif ($subject =="empty") {
  echo '<div class="errors">';
  echo "Please select a subject!";
  echo '</div>';
 }

 elseif (!$message) {
  echo '<div class="errors">';
  echo "Please enter a message!";
  echo '</div>';
 }

 else {
 mail('[email protected]', "$subject >> $name", $message, "From: $email");
 echo '<div class="complete">';
 echo "Your message has been sent! &mdash; We will reply as soon as we get to your message.";
 echo '</div>';
 }
}

  echo "<div class=\"title\">Contact Form</div>\n";
  echo "<form method=\"post\" name=\"contact\" action=\"form.php\">\n";
  echo "<p><label for=\"name\">Name:*<br /></label>\n";
  echo "<input class=\"onebartext\" name=\"name\" type=\"text\"  id=\"name\" tabindex=\"2\" value=\"$name\" /></p>\n";
echo "<br /><p><label for=\"email\">Email:*<br /></label>\n";
echo "<input class=\"onebartext\" name=\"email\" type=\"text\" id=\"email\" tabindex=\"2\" value=\"$email\" /></p>\n";

echo "<label for=\"subject\">Subject:*<br /></label>\n";
echo "<select name=\"subject\" class=\"form_box_s\">\n";
echo "<option value=\"empty\"></option>\n";

echo "<option value=\"[Contact Form]-Question\">Question Regarding Your Services</option>\n";
echo "<option value=\"[Contact Form]-Other\">Other (be specific in message)</option>\n";
echo "</select>\n";

echo "<p><label for=\"message\">Message:*<br />\n";

echo "<textarea class=\"textboxes\" name=\"message\" id=\"message\" tabindex=\"3\" rows=\"6\">$message</textarea>\n";
echo "</label></p>\n";

echo "<input class=\"form_box_submit\" type=\"submit\" name=\"submit\" value=\"Submit Your Message.\" tabindex=\"4\" />\n";
echo "</form>\n";
?>

Remember, I want you to have learned a lot from this tutorial, I didn't make a downloadable copy of form.php because I want you to create it and I want you to have learned, and I want you to say "I created this script, I created this form!". You can do anything with this form, you can even expand it and add security captcha, customize the css, add more input boxes, more drop-down menus, more texareas. Be creative, I'd like to see what you've done to it as-well. I want to see how creative you guys can get.

If you have any questions, comments, complaints, do post them up. I developed all the code within this thread, and put it all together without giving it a try. The form is secure, and ready for commercial use. I've checked the code multiple times to see if I missed anything, but it seems that it's all good and didn't notice any bugs.
Best Regards.
Very nice. You explained the code a lot which is great for beginners. I'm sure some will find it useful and more will find it a good learning tool Wink.
WOW! That's a detailed tutorial just from looking at it, I shall use in the future.. might take a while to read over..
Toungue
Nice tutorial!
Thanks for your comments guys, much appreciated.


(2008-09-18, 08:21 PM)NetSage Wrote: [ -> ]Very nice. You explained the code a lot which is great for beginners. I'm sure some will find it useful and more will find it a good learning tool Wink.

It is based for beginners who don't have PHP knowledge. However, in the tutorial, I expect that the reader has a fairly good knowledge of html.
Best Regards.
wow thanx man Smile

it ll help quite a bit as I am going after PHP these days.
(2008-09-19, 01:39 AM)MyBBmodding Wrote: [ -> ]wow thanx man Smile

it ll help quite a bit as I am going after PHP these days.

Glad you found it useful. Smile
imho echo is very sloppy to use for multiple lines especially if there is very little php inside it.

Your code:
Quote:<?php
echo "<div class=\"title\">Contact Form</div>\n";
echo "<form method=\"post\" name=\"contact\" action=\"form.php\">\n";
echo "<p><label for=\"name\">Name:*<br /></label>\n";
echo "<input class=\"onebartext\" name=\"name\" type=\"text\" id=\"name\" tabindex=\"2\" value=\"$name\" /></p>\n";
echo "<br /><p><label for=\"email\">Email:*<br /></label>\n";
echo "<input class=\"onebartext\" name=\"email\" type=\"text\" id=\"email\" tabindex=\"2\" value=\"$email\" /></p>\n";
?>

How I would do it.
Quote:<div class="title">Contact Form</div>
<form method="post" name="contact" action="form.php">
<p><label for="name">Name:*<br /></label>
<input class="onebartext" name="name" type="text" id="name" tabindex="2" value="<?=$name;?>" /></p>
<br /><p><label for="email">Email:*<br /></label>
<input class="onebartext" name="email" type="text" id="email" tabindex="2" value="<?=$email;?>" /></p>

imho that's a lot neater..notice I used for the variables: <?=$email;?>

That's a quick method to echo a variable with shorthand php.

Most of the problem I have is trying to escape all that and then any typo creates an error. The beauty of php is that you can go into html mode and back to php mode at any time.
(2008-09-19, 06:12 AM)labrocca Wrote: [ -> ]Most of the problem I have is trying to escape all that and then any typo creates an error. The beauty of php is that you can go into html mode and back to php mode at any time.

Best way - especially if you're using something like Dreamweaver or a WYSIWYG editor.

There's also:

// Echo, or not to echo... that is the question... Alternative: print()
echo "<div class=\"title\">Contact Form</div>
<form method=\"post\" name=\"contact\" action=\"form.php\">
<p><label for=\"name\">Name:*<br /></label>
<input class=\"onebartext\" name=\"name\" type=\"text\" id=\"name\" tabindex=\"2\" value=".$name." /></p>
<p><label for=\"email\">Email:*<br /></label>
<input class=\"onebartext\" name=\"email\" type=\"text\" id=\"email\" tabindex=\"2\" value=".$email." /></p>";

Apparently, according to books I've read, that's a preferred way - but only if it is defined to a variable. Undecided
Most of the problem I have is trying to escape all that and then any typo creates an error. The beauty of php is that you can go into html mode and back to php mode at any time.

You're absolutely right. However, so I won't cause any confusion between bouncing back (closing the php tag and opening it back again), I decided to just echo the entire thing. When you develop using php for quite a while, errors become less likely to happen. After I finished writing the tutorial, I decided to copy the code and put it in a new php file so I can see if their are any bugs in it. The only thing that went wrong, was I forgot to add the verification for the drop down menu, but everything else went smoothly.

Sloppy, I disagree.