Lesson 13 โข Expert
Security Best Practices ๐
Defend against SQL injection, XSS, and CSRF โ learn password hashing, input validation, secure headers, and file upload protection.
What You'll Learn in This Lesson
- โข SQL Injection: how it works and how to prevent it
- โข XSS: stopping malicious script injection
- โข CSRF: protecting forms with tokens
- โข Password hashing with password_hash/verify
- โข Secure headers, file upload safety, and the security checklist
Try It: Understanding Attacks
See how SQL injection, XSS, and CSRF attacks work and how to prevent them
// PHP Security: Understanding Attacks
console.log("=== The OWASP Top 3 for PHP ===");
console.log();
console.log("1๏ธโฃ SQL INJECTION");
console.log("โโโโโโโโโโโโโโโโโ");
console.log();
console.log("Attack: Inject malicious SQL through user input");
console.log();
console.log("โ Vulnerable code:");
console.log(' $sql = "SELECT * FROM users WHERE email = \'$email\'";');
console.log();
console.log("Attack input: ' OR 1=1 --");
console.log("Result query: SELECT * FROM users WHERE email = '' OR 1=1
...Try It: Defensive Techniques
Hash passwords, validate input, set security headers, and secure file uploads
// PHP Security: Defensive Techniques
console.log("=== Password Security ===");
console.log();
console.log("โ NEVER store plain text passwords!");
console.log("โ NEVER use MD5 or SHA1 for passwords!");
console.log();
console.log("โ
Use password_hash() and password_verify():");
console.log();
console.log(" // Registration: hash the password");
console.log(" $hash = password_hash($password, PASSWORD_DEFAULT);");
console.log(" // Store $hash in database (60+ chars)");
console.log();
console.log
...โ ๏ธ Common Mistakes
password_hash() which uses bcrypt/argon2 (intentionally slow).photo.jpg.php could be a PHP script! Always check the MIME type and rename uploads.๐ Quick Reference โ Security
| Attack | Prevention |
|---|---|
| SQL Injection | Prepared statements (PDO) |
| XSS | htmlspecialchars() |
| CSRF | Session-based tokens |
| Weak passwords | password_hash() + verify() |
| Session fixation | session_regenerate_id() |
| File upload | MIME check + rename + move outside webroot |
๐ Lesson Complete!
You now know how to secure PHP applications! Next, learn how to build and consume REST APIs with JSON.
Sign up for free to track which lessons you've completed and get learning reminders.