PHP form validation is a critical aspect of web development to ensure that user input meets specific criteria or constraints before processing it further. Here’s an overview of PHP form validation techniques:
$_POST
or $_GET
).<?php $errors = [];
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$username = $_POST["username"];
$password = $_POST["password"]; // Validate username
if (empty($username)) {
$errors["username"] = "Username is required";
} elseif (!preg_match("/^[a-zA-Z0-9_]{4,20}$/", $username)) {
$errors["username"] = "Username must be 4-20 characters and alphanumeric";
}
// Validate password
if (empty($password)) {
$errors["password"] = "Password is required";
} elseif (strlen($password) < 8) {
$errors["password"] = "Password must be at least 8 characters long";
}
// If no errors, process data
if (empty($errors)) {
// Process form data (e.g., authenticate user)
// Redirect user or display success message
} } ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="text" name="username" value="<?php echo isset($_POST['username']) ? $_POST['username'] : ''; ?>">
<span class="error"><?php echo isset($errors["username"]) ? $errors["username"] : ''; ?></span>
<input type="password" name="password"> <span class="error"><?php echo isset($errors["password"]) ? $errors["password"] : ''; ?></span>
<input type="submit" value="Submit">
</form>
In addition to validation, it’s essential to sanitize user input to prevent SQL injection, XSS attacks, and other security vulnerabilities. Use functions like htmlspecialchars()
and mysqli_real_escape_string()
to sanitize input before using it in SQL queries or output.
Server-side form validation with PHP is crucial for building robust and secure web applications. By implementing proper validation techniques, you can enhance the reliability and usability of your web forms while mitigating potential security risks.