What are the best practices for handling user input, such as email addresses, to prevent potential errors in PHP code?

To prevent potential errors when handling user input such as email addresses in PHP, it is important to validate the input to ensure it meets the expected format. One common approach is to use PHP's filter_var function with the FILTER_VALIDATE_EMAIL filter to check if the input is a valid email address. Additionally, it is recommended to sanitize the input to prevent any malicious code injection.

$email = $_POST['email'];

// Validate email address
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Sanitize the input
    $sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL);
    // Process the email address
} else {
    // Handle invalid email address
}