What are common pitfalls to avoid when implementing a search function in PHP to prevent XSS vulnerabilities?
When implementing a search function in PHP, it is crucial to sanitize user input to prevent XSS vulnerabilities. Common pitfalls to avoid include not properly escaping user input before displaying it on the page, not validating input data, and not using prepared statements when querying the database.
// Sanitize user input to prevent XSS vulnerabilities
$search_query = htmlspecialchars($_GET['search_query']);
// Validate input data
if (empty($search_query)) {
echo "Please enter a search query.";
} else {
// Use prepared statements when querying the database
$stmt = $pdo->prepare("SELECT * FROM products WHERE name LIKE :search_query");
$stmt->execute(['search_query' => "%$search_query%"]);
// Display search results
while ($row = $stmt->fetch()) {
echo $row['name'] . "<br>";
}
}