PHP
HTML Escaping User Input to Prevent XSS
Learn to prevent Cross-Site Scripting (XSS) attacks by properly escaping user-provided data before rendering it in HTML, ensuring secure web applications.
function escapeHtml(string $data): string {
return htmlspecialchars($data, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
// Example usage:
$user_input = "<script>alert('You've been hacked!');</script><b>Hello!</b>";
$safe_output = escapeHtml($user_input);
echo $safe_output; // Outputs: <script>alert('You've been hacked!');</script><b>Hello!</b>
How it works: This PHP snippet demonstrates how to prevent Cross-Site Scripting (XSS) vulnerabilities by escaping user-provided input using `htmlspecialchars()`. The function converts special characters like `<`, `>`, `&`, `"`, and `'` into their corresponding HTML entities. This ensures that malicious scripts embedded in user input are rendered as text rather than executable code in the browser, thereby safeguarding the application and its users.