Our initial step involves setting up a basic html form. We'll be submitting via the 'post' method, which passes the form parameters directly in the request (not within the url string).
<form method="post" action="">
Name: <input type="text" name="name" />
Email: <input type="text" name="email" />
How did you hear about us?
<input type="submit" value="Submit" name="action" />
Besides signifying the 'post' method inside the html element, you also have to define where the form submission goes within the action element. While you could have it submit to a separate URL, it is much easier just to have the form submit to itself. Now we can place the form submission logic at the top of the this file instead of tucked away somewhere else.
if(isset($_POST['action']) && $_POST['action'] == 'Submit')
if(isset($_POST['name']) && strlen($_POST['name']) > 0)
$name = $_POST['name'];
if(isset($_POST['email']) && strlen($_POST['email']) > 0)
$email = $_POST['email'];
($_POST['hear_about'] == 1) || ($_POST['hear_about'] == 2))
$hear_about = $_POST['hear_about'];
if(isset($name) && isset($email) && isset($hear_about)
'New contact submission!',
$form_success = true;
$form_success = false;
Since the form is being submitted by the 'post' method, all of the form elements are passed within the php $_POST superglobal. You can grab the value of each submitted value by accessing the name of the element as a key in the $_POST array. The validation is simple in this example - only checking to make sure that the post parameter was sent to this code and has a string value. You can easily add more complicated checks for the structure of the email input, length of the name, etc.
You may have noticed that this script sets a variable called $form_success. It could actually have three separate values: unset, true, or false. If the value is unset, then you would just display the form. If the value is true, hide the form and show a thank you message. If the value is false, show the form and show an error message.
And that's how you create a very basic form with simple validation. In the next post we'll go over some best practices for forms, digging deeper into the thought process behind the handling and behaviors.