TL;DR
This guide shows you how to protect your website from common attacks like Cross-Site Scripting (XSS) and SQL Injection. We’ll cover input validation, output encoding, and password hashing.
1. Understanding the Threats
- Cross-Site Scripting (XSS): Attackers inject malicious scripts into your website that run in a user’s browser. This can steal cookies, redirect users, or modify content.
- SQL Injection: Attackers insert malicious SQL code into your database queries to access, modify, or delete data.
2. Input Validation
Never trust user input! Always validate it before using it in your application.
- Whitelisting: Define what characters and formats are allowed. Reject anything else. This is the most secure approach.
- Blacklisting: Identify dangerous characters or patterns and reject them. Less reliable than whitelisting, as attackers can find ways around filters.
- Example (PHP): Validate an email address.
3. Output Encoding
When displaying user input on your website, encode it to prevent XSS attacks.
- HTML Encoding: Convert special characters (e.g., <, >, &) into their HTML entities.
- JavaScript Encoding: Encode characters that have special meaning in JavaScript.
- URL Encoding: Encode characters for use in URLs.
4. Preventing SQL Injection
Protect your database queries from malicious code.
- Prepared Statements (Parameterized Queries): Use placeholders for user input and let the database handle escaping.
prepare("SELECT * FROM users WHERE username = ?"); $stmt->execute([$username]); ?> - Escaping User Input: If you can’t use prepared statements, escape special characters before using them in queries. However, this is less secure than prepared statements.
quote($username); $stmt = $pdo->query("SELECT * FROM users WHERE username = " . $safeUsername); ?>
5. Password Hashing
Never store passwords in plain text! Hash them using a strong hashing algorithm.
- Use a Strong Algorithm: bcrypt or Argon2 are recommended.
- Salting: Automatically handled by modern hashing functions like bcrypt.
- Verification: Use
password_verify()to check if a provided password matches the stored hash.
6. Additional Security Measures
- Keep Software Updated: Regularly update your CMS, plugins, and libraries to patch security vulnerabilities.
- Use a Web Application Firewall (WAF): A WAF can help block common attacks before they reach your application.
- Regular Security Audits: Have your website regularly audited for security flaws.

