Home >Backend Development >PHP Tutorial >PHP form processing: request parameter acquisition and processing
PHP form processing: request parameter acquisition and processing
In web development, forms are a very common way of interaction. When a user submits form data in the browser, the server needs to obtain the data and process it accordingly. This article will introduce the basic methods of obtaining and processing form data using PHP, and provide code examples.
$_POST
or $_GET
. $_POST
is used to obtain form data submitted through the POST method, $_GET
is used to obtain form data submitted through the GET method. Sample code 1: Get the form data submitted through the POST method
$name = $_POST['name']; $email = $_POST['email']; $password = $_POST['password']; // 其他表单字段
Sample code 2: Get the form data submitted through the GET method
$name = $_GET['name']; $email = $_GET['email']; $password = $_GET['password']; // 其他表单字段
Sample code 3: Verify the validity of form data
if (empty($name)) { echo "姓名不能为空"; } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "邮箱格式不正确"; } if (strlen($password) < 6) { echo "密码长度不能小于6位"; } // 其他表单字段的验证
Sample code 4: Insert form data into the database
// 假设有一个名为"users"的数据表 $sql = "INSERT INTO users (name, email, password) VALUES ('$name', '$email', '$password')"; if ($conn->query($sql) === TRUE) { echo "插入数据成功"; } else { echo "插入数据失败: " . $conn->error; }
$_POST
or $_GET
variables to obtain the values of multiple options. Sample code 5: Get the value of the multi-select box or check box
$colors = $_POST['colors']; if (!empty($colors)) { echo "选择的颜色是:" . implode(', ', $colors); } else { echo "没有选择颜色"; }
$_FILES
superglobal variable to handle uploaded files. Sample code 6: File upload processing
$targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["file"]["name"]); if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) { echo "文件上传成功"; } else { echo "文件上传失败"; }
The above is the basic PHP form processing method and sample code. Based on actual needs, we can perform corresponding data verification and processing according to specific circumstances. To ensure website security, it is important to perform data verification and prevent attacks such as SQL injection.
The above is the detailed content of PHP form processing: request parameter acquisition and processing. For more information, please follow other related articles on the PHP Chinese website!