What are the best practices for handling user input in PHP forms to prevent security vulnerabilities?

One of the best practices for handling user input in PHP forms to prevent security vulnerabilities is to always sanitize and validate user input before processing it. This can help prevent SQL injection, cross-site scripting (XSS), and other common security vulnerabilities.

// Example of sanitizing and validating user input in a PHP form
$username = htmlspecialchars($_POST['username']); // Sanitize user input
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL); // Validate email input

// Further validation and processing of the sanitized and validated input
if ($email) {
    // Process the input
} else {
    // Handle invalid input
}