What are the potential pitfalls of not restricting input to alphanumeric characters in PHP?

Allowing input that includes special characters can lead to security vulnerabilities such as SQL injection or cross-site scripting attacks. To prevent this, it is important to restrict input to alphanumeric characters only by using regular expressions to validate the input before processing it in your PHP code.

// Validate input to ensure it contains only alphanumeric characters
$input = $_POST['input'];

if (!preg_match('/^[a-zA-Z0-9]+$/', $input)) {
    // Input contains invalid characters, handle error
    echo "Input must contain only alphanumeric characters";
} else {
    // Input is valid, proceed with processing
    // Your code here
}