PHP Tutorial – Form Handling

In this PHP language tutorial we will look at PHP forms and form handling. We will use the PHP $_GET and $_POST variables to retrieve information from the HTML form. You use forms to get user input.

PHP Form Handling

You have to be aware of the following when dealing with HTML forms and PHP: any form element in an HTML page will automatically be available to the PHP scripts that you use.

So let’s look at an example form:


<html>
<body>

<form action="test.php" method="post">
Your name: <input type="text" name="yourname" />
<input type="submit" />
</form>

</body>
</html>

The HTML code above will display a form on your screen with the one input box and a submit button. If you click on the submit button the PHP script test.php is called. In this second file test.php we add the following PHP code:


<html>
<body>

Welcome <?php echo $_POST["yourname"]; ?>!

</body>
</html>

So if you click on the submit button the PHP script test.php is called. In this second script we echo the name you have typed using the name “yourname” that points to the $_POST array element with value you just have written in the input box. (The names of the form fields will automatically be the keys in the $_POST array.)

Note: when you work with forms you should never trust what people input. Always check the input for malicious code or unexpected input. Also, where possible you should always use $_POST function, but more on that later.

In the next two we will look at the built-in PHP $_GET Function and PHP $_POST Function

This entry was posted in PHP Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There is currently one response to “PHP Tutorial – Form Handling”

Why not let us know what you think by adding your own comment!

  1. hamster balls on December 9th, 2011:

    hamster balls…

    […]PHP Tutorial – Form Handling | CodingUnit Programming Tutorials[…]…