PHP

Implement Comprehensive Server-Side Input Validation

Validate all user input comprehensively on the server-side, checking data types, formats, and constraints to prevent various vulnerabilities and ensure data integrity.

function validateUserData($data) {
    $errors = [];

    // Validate 'username'
    if (empty($data['username'])) {
        $errors[] = "Username is required.";
    } elseif (!preg_match("/^[a-zA-Z0-9_]{3,20}$/", $data['username'])) {
        $errors[] = "Username must be 3-20 characters long and contain only letters, numbers, or underscores.";
    }

    // Validate 'email'
    if (empty($data['email'])) {
        $errors[] = "Email is required.";
    } elseif (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format.";
    }

    // Validate 'age'
    if (empty($data['age'])) {
        $errors[] = "Age is required.";
    } elseif (!filter_var($data['age'], FILTER_VALIDATE_INT, ["options" => ["min_range" => 18, "max_range" => 120]])) {
        $errors[] = "Age must be an integer between 18 and 120.";
    }

    // Validate 'password' (basic length check, not hashing)
    if (empty($data['password'])) {
        $errors[] = "Password is required.";
    } elseif (strlen($data['password']) < 8) {
        $errors[] = "Password must be at least 8 characters long.";
    }

    return $errors;
}

// Example usage:
$post_data = [
    'username' => 'test_user123',
    'email' => '[email protected]',
    'age' => 25,
    'password' => 'securePass123'
];

$validation_errors = validateUserData($post_data);

if (!empty($validation_errors)) {
    echo "Validation Errors:
" . implode("
", $validation_errors);
} else {
    echo "Data is valid. Proceed with processing.
";
    // Further processing (e.g., save to database)
}

$invalid_data = [
    'username' => 'ab',
    'email' => 'invalid-email',
    'age' => 15,
    'password' => 'short'
];
$invalid_errors = validateUserData($invalid_data);
if (!empty($invalid_errors)) {
    echo "
Validation Errors for invalid data:
" . implode("
", $invalid_errors);
}
How it works: This PHP function `validateUserData` demonstrates robust server-side input validation. It checks common fields like `username`, `email`, `age`, and `password` for emptiness, format (using `preg_match` and `filter_var`), and range constraints. This goes beyond simple XSS sanitization by ensuring that data conforms to expected business rules and data types, preventing a wide array of vulnerabilities, including malformed data storage, logic errors, and certain types of injection attacks. All incoming data should be thoroughly validated on the server.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs