What are the best practices for securely handling user input in PHP scripts?

When handling user input in PHP scripts, it is crucial to sanitize and validate the input to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. One of the best practices is to use functions like htmlspecialchars() or mysqli_real_escape_string() to sanitize user input before using it in database queries or displaying it on the webpage.

// Sanitize user input using htmlspecialchars()
$userInput = htmlspecialchars($_POST['user_input']);

// Validate user input using regular expressions
if (preg_match("/^[a-zA-Z0-9]+$/", $userInput)) {
    // Input is valid, proceed with processing
} else {
    // Input is invalid, handle the error
}