PHP Form Processing
One very important thing to note is that when processing HTML forms, PHP can automatically turn form elements from the HTML page into available for PHP scripts use.
Example
The following example contains an HTML form with two input boxes and a submit button.
form.html file code is as follows:
<html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <form action="welcome.php" method="post"> 名字: <input type="text" name="fname"> 年龄: <input type="text" name="age"> <input type="submit" value="提交"> </form> </body> </html>
When the user fills out the above form and clicks the submit button, the form data will be sent to the PHP file named "welcome.php" :
welcome.php file looks like this:
欢迎 <?php echo $_POST["fname"]; ?>!<br> 你的年龄是 <?php echo $_POST["age"]; ?> 岁。
Form Validation
User input should be validated whenever possible (via the client end script). Browser validation is faster and reduces the load on the server.
If user input needs to be inserted into the database, you should consider using server validation. A good way to validate a form on the server is to pass the form to itself, rather than jumping to a different page. This way users can get error messages on the same form page. It will be easier for users to find errors.
Process the GET request. The function implemented is to display "Hello XXX" on the page after entering the name and create the html file hello.html.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>欢迎</title> </head> <body> <form action="hello.php" method="get"> 姓名<input name="name" type="text"/> <input type="submit"/> </form> </body> </html>
Create PHP file hello.php
<?php header("Content-type: text/html; charset=utf-8"); if(isset($_GET['name'])&&$_GET['name']){//如果有值且不为空 echo 'Hello '.$_GET['name']; }else{ echo 'Please input name'; }
Process POST request, implement a simple addition function, create html file add.html
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>相加</title> </head> <body> <form action="add.php" method="post"> <input name="num1" type="text"/> + <input name="num2" type="text"/> <input type="submit" value="相加"/> </form> </body> </html>
Create PHP file add. php
<?php if($_POST['num1']&&$_POST['num2']){ echo $_POST['num1']+$_POST['num2']; }else{ echo '请不要空值'; }
Post request puts the form data in the http request body, and there is no length limit
form action="" means: form is the form, action is The redirection address, that is, where the form needs to be submitted
Next Section