The correct way to post and echo form values
In this tutorial, we will post a form value and echo it back. But taking care to escape the values using htmlspecialchars() in order to prevent cross-site scripting attacks.
A demo here shows the form…
which when submitted will return …
1. Create an index.php in a folder with the following…
This is a basic html 5 page with a form that will “post” to another PHP file called “confirmation.php”. Note the method=”post” and action=”confirmation.php” in the <form> element.
Within the form, we have a textbox (input element of type=”text”) with name attribute of “greeting”. The name attribute will be how we reference this form value later.
Finally, we have a submit button with <input type=”submit”> that will submit the form.
2. The form will submit to the confirmation.php page. Sometimes beginners write the confirmation.php page as follows. However, this is NOT correct.
This is wrong way to submit and echo form values. It is dangerous, because it is vulnerable to cross-site scripting attacks. You see that it is echoing out exactly whatever the user had typed in via the super global $_POST[‘greeting’].
Never trust user input, and never output it directly out to an HTML page. All user inputs must be “escaped”. That means that special HTML characters are turned into HTML entities. This means that if the user enters “<script>” into the input box, the angle bracket are turned into their HTML entities equivalent which are < and >
Because they are turned into their HTML entities, the browser will not see them as angle brackets and will not see the script tag and will not run the user injected script (which potentially can be harmful).
3. We escape the form values by using the PHP function htmlspecialschars() as in …
Now even when user enters a malicious entry like…
It is rendered safe. Do view source on your browser and you see …
We continue this example in the next tutorial.