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.