What best practices should be followed when handling user input in PHP scripts to prevent syntax errors and vulnerabilities?

When handling user input in PHP scripts, it is crucial to sanitize and validate the input to prevent syntax errors and vulnerabilities such as SQL injection or cross-site scripting attacks. One best practice is to use functions like htmlspecialchars() to escape special characters and prevent script injections. Additionally, validating user input against expected formats can help ensure that only safe and expected data is processed.

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

// Validate user input against expected format
if (preg_match("/^[a-zA-Z0-9]+$/", $userInput)) {
    // Input is safe to use
} else {
    // Handle invalid input
}