The use of POST requests in PHP is a common operation in website development. Data can be sent to the server through POST requests, such as form data, user information, etc. Proper use of POST requests can ensure data security and accuracy. The following will introduce the correct usage of POST requests in PHP and provide specific code examples.
In PHP, the data submitted through the POST method can be obtained by using the $_POST
global variable. The POST method sends form data to the server in POST mode, and the data is encapsulated in the message body of the HTTP request. On the server side, these data can be obtained through $_POST
, and then processed accordingly.
When using a form to submit data in the front-end page, you need to change the form's method# The ## attribute is set to
post to ensure that the data is sent to the server in POST mode. Receiving POST data in PHP can be obtained through the
$_POST global variable. The following is a simple example:
<form action="submit.php" method="post"> <input type="text" name="username"> <input type="password" name="password"> <button type="submit">提交</button> </form>
in submit.php
$_POSTGet the submitted data:
$username = $_POST['username']; $password = $_POST['password'];
mysqli_real_escape_string, or use prepared statements to perform database operations. The following is an example:
$username = mysqli_real_escape_string($conn, $_POST['username']);
filter_var to filter and verify data, such as verifying email format, verifying mobile phone number format, etc. The example is as follows:
$email = $_POST['email']; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "邮箱格式不正确"; }
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = mysqli_real_escape_string($conn, $_POST['username']); $password = mysqli_real_escape_string($conn, $_POST['password']); // 数据验证 if (empty($username) || empty($password)) { echo "用户名和密码不能为空"; exit; } // 执行相应操作,例如数据库插入、用户认证等 echo "数据提交成功!"; } ?>
The above is the detailed content of Correct usage of POST request in PHP. For more information, please follow other related articles on the PHP Chinese website!