How can whitelisting be used effectively to enhance security when handling user input in PHP?

Whitelisting can be used effectively to enhance security when handling user input in PHP by only allowing specified, safe input to be processed. This can help prevent malicious input, such as SQL injection or cross-site scripting attacks, from causing harm to the application. By defining a list of allowed characters or patterns, whitelisting ensures that only valid input is accepted.

// Example of whitelisting input to only allow alphanumeric characters
$user_input = $_POST['user_input'];

if (preg_match('/^[a-zA-Z0-9]*$/', $user_input)) {
    // Process the input
} else {
    // Handle invalid input
}