Web Security Best Practices

From the archive: a general guide from February 2024, tidied and kept for reference.

Web Security Best Practices

Two Risks from the OWASP Top 10

Injection Attacks

SQL, NoSQL, OS, and LDAP injection flaws


// Vulnerable Code
$query = "SELECT * FROM users WHERE username = '$username'";

// Secure Code
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);

Authentication Failures

Session management and authentication flaws

  • Offer multi-factor authentication
  • Hash passwords with a slow algorithm such as Argon2 or bcrypt
  • Expire sessions and issue a new session ID at login

Cross-Site Scripting (XSS) Prevention


// Unsafe output
echo $userInput;

// Safe output
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

// Content Security Policy
header("Content-Security-Policy: default-src 'self';");

Security Headers

X-Frame-Options

X-Frame-Options: SAMEORIGIN

Prevents clickjacking by stopping other sites from framing your pages (the CSP frame-ancestors directive does the same in newer browsers)

X-XSS-Protection

X-XSS-Protection: 0

Turns off the old browser XSS filter. Current browsers have removed it, and the old 1; mode=block setting could itself be abused, so rely on output escaping and a Content Security Policy instead