One of the most useful pages of any website is the html contact form page. No website should be without a contact or feedback form. We will here tell you how to create a simple form using PHP.
PHP – A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button. You can add as many number of fields you want, as per your requirement.
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named “welcome.php”. The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The “welcome.php” looks like this:
The output could be something like this:
Your email address is email@example.com
The same result could also be achieved using the HTTP GET method.
and “welcome_get.php” looks like this:
Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, …)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Now we we learn about, How to validate a PHP form.
PHP Form Validation
The validation rules for the form above are as follows:
Now the code goes like this:
Validate Form Data With PHP
The first thing we will do is to pass all variables through PHP’s htmlspecialchars() function.
When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:
– this would not be executed, because it would be saved as HTML escaped code, like this:
The code is now safe to be displayed on a page or inside an e-mail.
We will also do two more things when the user submits the form:
Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again).
We name the function test_input() shown in above.
Notice that at the start of the script, we check whether the form has been submitted using $_SERVER[“REQUEST_METHOD”]. If the REQUEST_METHOD is POST, then the form has been submitted – and it should be validated. If it has not been submitted, skip the validation and display a blank form.
However, in the example above, all input fields are optional. The script works fine even if the user do not enter any data.