PHP Study Notes: Form Processing and Data Validation
In web development, forms are one of the important components for users to interact with the website. When users fill out forms and submit data on the website, the website needs to process and verify the submitted data to ensure the accuracy and security of the data. This article will introduce how to use PHP to process forms and perform data validation, and provide specific code examples.
Code example:
<form action="form.php" method="post"> <input type="text" name="username" placeholder="请输入用户名"> <input type="password" name="password" placeholder="请输入密码"> <input type="submit" value="提交"> </form>
In the above code, we create a form containing username and password input boxes, and set the form's submission method to POST, and the target address is "form.php". When the user clicks the submit button, the form data will be submitted to "form.php" for processing. In "form.php", we can use $_POST['username'] and $_POST['password'] to get the values of username and password.
if (empty($_POST['username'])) { echo "用户名不能为空"; }
if (strlen($_POST['username']) < 6 || strlen($_POST['username']) > 20) { echo "用户名长度必须在6-20个字符之间"; }
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { echo "请输入有效的邮箱地址"; }
$username = mysqli_real_escape_string($conn, $_POST['username']); $password = mysqli_real_escape_string($conn, $_POST['password']);
In the above example, we used PHP's built-in filter_var function to perform data format verification, and used the mysqli_real_escape_string function to filter user input.
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { // 数据预处理 $username = $_POST['username']; $password = $_POST['password']; // 数据验证 if (empty($username) || empty($password)) { echo "用户名和密码不能为空"; } elseif (strlen($username) < 6 || strlen($username) > 20) { echo "用户名长度必须在6-20个字符之间"; } else { // 数据插入或其他业务处理 // ... echo "表单提交成功"; } } ?> <form action="" method="post"> <input type="text" name="username" placeholder="请输入用户名"> <input type="password" name="password" placeholder="请输入密码"> <input type="submit" value="提交"> </form>
In the above example, we Determine whether the form is submitted by judging whether $_SERVER['REQUEST_METHOD'] is equal to 'POST'. Then, we perform data preprocessing and verification, and execute corresponding logic based on the verification results. If the verification passes, we can insert the data into the database or perform other business processing.
Summary
Through the study of this article, we have learned how to use PHP to process forms and perform data validation. Form processing and data validation are a very important part of website development, which can ensure the accuracy and security of data submitted by users. I hope the content of this article can be helpful to PHP beginners.
The above is the detailed content of PHP study notes: form processing and data validation. For more information, please follow other related articles on the PHP Chinese website!