Skip to content
PHP Logo

In what ways can PHP form validation be implemented to ensure that user input is properly processed and displayed on the screen?

To ensure that user input is properly processed and displayed on the screen, PHP form validation can be implemented by checking for empty fields, validating email addresses, sanitizing input to prevent SQL injection attacks, and using regular expressions to enforce specific formats for input data.

php
// Check for empty fields
if(empty($_POST['username']) || empty($_POST['password'])) {
    echo "Please fill out all fields";
}

// Validate email address
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email address";
}

// Sanitize input to prevent SQL injection
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);

// Use regular expressions to enforce specific formats
if(!preg_match("/^[a-zA-Z0-9]{6,12}$/", $_POST['username'])) {
    echo "Username must be between 6-12 characters and alphanumeric";
}