How can PHP be used to secure a search function against potential abuse like XSS?

To secure a search function against potential abuse like XSS, input validation and output escaping are crucial. Input validation ensures that only expected data types and formats are accepted, while output escaping prevents any user input from being interpreted as code. By implementing these measures, you can protect your application from malicious scripts being injected through the search function.

$searchTerm = $_GET['search']; // Assuming search term is passed through GET parameter

// Input validation to ensure search term is a string
if (!is_string($searchTerm)) {
    die('Invalid search term');
}

// Output escaping to prevent XSS attacks
echo htmlspecialchars($searchTerm, ENT_QUOTES, 'UTF-8');