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();
Related Questions
- What are the best practices for converting date strings into Date objects in PHP to ensure accurate comparison and manipulation of dates?
- Are there any best practices to follow when reading directories and creating arrays of file names in PHP?
- How can PHP be used to pass and retrieve questionnaire responses using $_POST?