Backend Development 4 min read

PHP Form Data Validation and Filtering Techniques

This article explains how to use PHP functions to validate required fields, email and phone formats, and to filter HTML tags, special characters, and prevent SQL injection, providing clear code examples for each technique.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP Form Data Validation and Filtering Techniques

As the Internet evolves, forms have become a crucial way for users to interact with websites, and developers must ensure the safety and correctness of submitted data. Using PHP functions for validation and filtering helps prevent malicious input and data errors.

1. Data Validation

1.1 Validate Required Fields

Many forms contain mandatory fields that can be checked by determining whether they are empty. PHP functions empty() or isset() can be used for this purpose.

if (empty($_POST['username']) || empty($_POST['password'])) {
    echo "用户名和密码不能为空!";
    exit;
}

1.2 Validate Email Format

To verify that a user‑entered email address follows the correct format, use the filter_var() function together with the FILTER_VALIDATE_EMAIL filter.

$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "邮箱格式不正确!";
    exit;
}

1.3 Validate Phone Number Format

Phone numbers can be validated with a regular expression.

$phone = $_POST['phone'];
if (!preg_match("/^1[3456789]\d{9}$/", $phone)) {
    echo "手机号格式不正确!";
    exit;
}

2. Data Filtering

2.1 Filter HTML Tags

To prevent users from submitting malicious HTML or scripts, use strip_tags() to remove all HTML tags.

$content = $_POST['content'];
$filteredContent = strip_tags($content);

2.2 Filter Special Characters

Special characters can be escaped with htmlspecialchars() to avoid XSS attacks.

$content = $_POST['content'];
$filteredContent = htmlspecialchars($content);

2.3 Prevent SQL Injection

To guard against malicious SQL statements, escape user input using mysqli_real_escape_string() .

$username = $_POST['username'];
$password = $_POST['password'];
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);

These are common validation and filtering methods; developers can customize additional rules based on specific business and security requirements to improve user experience and protect website security.

backendSecurityPHPData Filteringform validation
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.