The correct way to post and echo form values

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

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…

post form example

post form example

which when submitted will return …

 

confirmation page

confirmation page

1.  Create an index.php in a folder with the following…

basic form

basic form

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.

wrong way to submit echo form values

wrong way to submit echo form values

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 &lt; and &gt;

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 …

correct form submission

correct form submission

Now even when user enters a malicious entry like…

malicious entry

malicious entry

It is rendered safe.  Do view source on your browser and you see …

safe html entities

safe html entities

We continue this example in the next tutorial.