Home >Backend Development >PHP Tutorial >How does php handle forms?
One very useful feature of PHP is the way it handles PHP forms. A very important principle to understand is that any element of the form automatically takes effect in the PHP script. See "External Variables in PHP" in this manual for details and examples of using forms in PHP. Here is an example of an HTML form:
<form action="action.php" method="post"> <p>姓名: <input type="text" name="name" /></p> <p>年龄: <input type="text" name="age" /></p> <p><input type="submit" /></p> </form>
There is nothing special about this form; no special identifiers are used. When the user fills out the form and clicks the submit button, the page action.php will be called. In this file, you can add the following:
Example #2 Print data from the form
你好,<?php echo htmlspecialchars ( $_POST [ 'name' ]); ?>。 你 <?php echo (int) $_POST [ 'age' ]; ?> 岁了。
The output of this script may be:
你好,Joe。你 22 岁了。
In addition to htmlspecialchars() and (int) part, it is obvious what this program does. htmlspecialchars() enables the special characters in HTML to be correctly encoded, so that users will not inject HTML tags or Javascript codes into the page. For example, for the age field, we clearly know it is a numeric value, so we convert it to an integer to automatically eliminate any unnecessary characters. You can also use PHP's filter extension to automatically complete this work. PHP will automatically set the $_POST['name'] and $_POST['age'] variables. Before this we used Super global variables $_SERVER, now we have introduced the super global variable $_POST, which contains all POST data. Please pay attention to the method of submitting data in our form. If the GET method is used, the information in the form will be stored in the superglobal variable $_GET. If you don't care about the source of the requested data, you can also use the superglobal variable $_REQUEST, which contains all GET, POST, COOKIE and FILE data.
It is also possible to handle XForms input in PHP, although users may prefer to use the long-standing and well-supported HTML forms. XForms is not yet suitable for beginners, but it may be of interest to users. The manual has a section in the "Features" chapter that gives a brief introduction to how to handle data received from XForum.
The above is the detailed content of How does php handle forms?. For more information, please follow other related articles on the PHP Chinese website!