Contemporary web is all about interactions. You submit some data and get a response back. It could be a post on Facebook, online payment, or selecting your city for weather forecast – this is all done by web forms.
<form action="results.php" method="post">
Form tag has two mandatory attributes – action and method.
During this lesson we will focus on the post method. We will have our form’s data posted (this is our action) to a separate file called result.php.
To be able to send any data to the server via our form we need some input tags.
The most common input tag is probably input of type text:
It produces a simple text box. Input needs name attribute, so we can target it, when retrieving form’s data. We also add a label next to each input – to make it easier for the user to understand what information he / she should insert to it:
Input type text are preferable options for generic short text fields. If you wish to use more specific types of text fields – like: email, url or number – it’s best to use the right type for the job. Read more about various HTML5 input types here:
If you want to have a text field that is bigger than one line, use textarea tag.
Now if we want to submit our form we need an input of type submit. This type of input looks like a button and user can actually click it:
Each of the form elements can also have required attribute – which makes it mandatory to fill this field, and placeholder attribute – which gives the user a hint of what he / she should put there.
Now let’s create a new file called results.php. This is where we pointed our form’s action to. Upon submission, browser will redirect to /results.php. The information from our form will be made available to the script on this page. We can retrieve it using special PHP system variable $_POST.
$_POST variable can read each form field by name:
$first_name = $_POST['first_name'];
$user_email = $_POST['email'];
$user_message = $_POST['message'];
//display posted values
What we put in square brackets [‘…’] is the name we gave our form’s elements: