What are the best practices for sanitizing user input in PHP to prevent code injection and other malicious activities?

To prevent code injection and other malicious activities, it is essential to sanitize user input in PHP by using functions like htmlentities() or htmlspecialchars() to encode special characters. Additionally, using prepared statements with parameterized queries when interacting with databases can help prevent SQL injection attacks.

// Sanitize user input using htmlentities()
$userInput = htmlentities($_POST['user_input'], ENT_QUOTES, 'UTF-8');

// Or sanitize user input using htmlspecialchars()
$userInput = htmlspecialchars($_POST['user_input'], ENT_QUOTES, 'UTF-8');

// Example of using prepared statements to prevent SQL injection
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $userInput);
$stmt->execute();