What are the best practices for handling user input validation and sanitization in PHP scripts?

User input validation and sanitization are crucial in PHP scripts to prevent security vulnerabilities such as SQL injection, cross-site scripting (XSS), and other forms of attacks. It is best practice to validate user input by checking for expected data types, lengths, and formats, and then sanitize the input to remove any potentially harmful characters.

// Example of validating and sanitizing user input in PHP
$userInput = $_POST['user_input'];

// Validate input
if (is_string($userInput) && strlen($userInput) <= 50) {
    // Sanitize input
    $sanitizedInput = filter_var($userInput, FILTER_SANITIZE_STRING);

    // Use the sanitized input in your script
    echo "Sanitized input: " . $sanitizedInput;
} else {
    echo "Invalid input";
}