PHP Security Basics: XSS and CSRF (Must Know)
Protect your PHP apps from common attacks with practical, beginner-friendly steps.
Security is not optional. Two common attacks in web apps are: - XSS (injecting scripts into HTML output) - CSRF (tricking a logged-in user to submit a request)
1) XSS protection (escape output)
If a user enters: `<script>alert(1)</script>` and you echo it directly, you may execute it.
### Always escape output ```php echo htmlspecialchars($comment, ENT_QUOTES, 'UTF-8'); ```
2) CSRF protection (token in forms)
### Step 1: Create token in session ```php session_start(); if (!isset($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(32)); } ```
### Step 2: Put token in form ```html <input type="hidden" name="csrf" value="<?php echo $_SESSION['csrf']; ?>"> ```
### Step 3: Validate token on submit ```php if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) { die("CSRF validation failed"); } ```
Why this matters
Most real PHP bugs happen because developers trust input or forget tokens.
Quick security checklist
- validate and sanitize input - escape output (XSS) - use prepared statements (SQL injection) - protect forms with CSRF tokens - hash passwords using password_hash
> Next set (30 more): Advanced topics like transactions, indexes, file uploads security, middleware style routing, Laravel fundamentals, and scaling patterns.