Are there any best practices for sanitizing user input in PHP to prevent security vulnerabilities like SQL injection or cross-site scripting?

To prevent security vulnerabilities like SQL injection or cross-site scripting, it's crucial to sanitize user input before using it in your PHP application. One best practice is to use prepared statements with parameterized queries for database interactions to prevent SQL injection attacks. Additionally, you can use functions like htmlspecialchars() or htmlentities() to encode user input and prevent cross-site scripting attacks.

// Sanitize user input to prevent SQL injection
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();

// Sanitize user input to prevent cross-site scripting
$cleanInput = htmlspecialchars($_POST['input'], ENT_QUOTES);
echo $cleanInput;