Home > Article > Backend Development > PHP Forms: Handling User Input Like a Pro
Key steps for handling form input in PHP include: Validating input to prevent malicious code. Check for errors to ensure users fill out all fields correctly. Store data securely to prevent unauthorized access. By using filters and prepared statements, you can create secure PHP forms that handle user input.
PHP Forms: Handling User Input Professionally
Introduction
PHP Forms are An important tool for interacting with users and collecting information. When handling user input, it's crucial to ensure it's valid and safe. This article will guide you step-by-step through processing form input in PHP, including practical examples.
Step 1: Validate input
Use PHP built-in functions such as filter_input
to filter and sanitize user input.
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
Step 2: Check for Errors
Use filter_has_var
and filter_input_array
to check for any typing errors.
if (filter_has_var(INPUT_POST, 'name') && filter_input_array(INPUT_POST, 'name', FILTER_VALIDATE_STRING)) { // 表单已正确提交 } else { // 显示错误消息 }
Step 3: Store data securely
Store user input in a database or other secure location. Use prepared statements to prevent SQL injection attacks.
$stmt = $db->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $stmt->bind_param("ss", $name, $email); $stmt->execute();
Practical Case: Contact Form
Create a PHP script to handle contact form submission:
<?php // 验证输入 $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); $message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING); // 检查错误 if (filter_has_var(INPUT_POST, 'name') && filter_input_array(INPUT_POST, 'message', FILTER_VALIDATE_STRING)) { // 存储数据 $stmt = $db->prepare("INSERT INTO messages (name, email, message) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $name, $email, $message); $stmt->execute(); // 显示成功消息 echo "消息已发送。谢谢您的联系。"; } else { // 显示错误消息 echo "请填写所有必需的字段。"; } ?>
The above is the detailed content of PHP Forms: Handling User Input Like a Pro. For more information, please follow other related articles on the PHP Chinese website!