Security essentials
Every public PHP site is attacked by bots daily. Almost all successful attacks use a handful of well-known mistakes, collected in the OWASP Top 10. This lesson shows each common vulnerability in PHP, what goes wrong, and the standard fix. The fixes are simple; the important part is applying them every time.
1. Cross-site scripting (XSS): escape output
If you print user input into HTML as-is, an attacker can submit HTML or JavaScript that then runs in other users' browsers, stealing their sessions or acting as them:
- Escape every value you print into HTML with
htmlspecialchars(ENT_QUOTESalso escapes quotes, which matters inside attributes). - Template engines (Blade's
{{ $x }}, Twig's{{ x }}) escape automatically. Know when you turn that off ({!! !!},|raw). - In JavaScript, use
json_encodewithJSON_HEX_TAG; in URLs,urlencode.
2. SQL injection: prepared statements
Covered in depth in Databases with PDO. In one line: never build SQL by joining strings with user input; always use placeholders:
3. Passwords: hash them properly
Never store passwords as plain text, and never use fast hashes like md5 or sha1 for them. Use password_hash, which picks a slow, salted algorithm (bcrypt, or Argon2id when available):
- The salt (random data mixed in) is stored inside the hash, so equal passwords get different hashes.
password_verifycompares safely (in constant time).- Also: limit login attempts, and support two-factor authentication for important accounts.
4. Cross-site request forgery (CSRF): tokens
A malicious site can make a logged-in user's browser submit a form to your site (for example "change email"), and the browser sends the session cookie along. The defence: every form includes a secret token that the other site can't know:
Also set session cookies with SameSite=Lax (or Strict), which stops most cross-site sends. Laravel and Symfony add CSRF tokens to forms automatically (@csrf in Blade).
5. Validate all input
Everything from the request ($_GET, $_POST, $_COOKIE, headers, uploaded files, JSON bodies) is controlled by the client. Check type, length and format on the server:
Use allow-lists (in_array($plan, ['free', 'pro'], true)) rather than trying to block bad values.
6. File uploads and paths
For uploads: check the size, detect the real type from the content (finfo_file), store files outside the web root or with a random name and a fixed extension, and never let uploads be executed as PHP.
7. Secrets, errors and configuration
// ✅ Read secrets from the environment, never from code in Git.
$dbPassword = getenv('DB_PASSWORD');
$apiKey = $_ENV['STRIPE_SECRET'] ?? throw new RuntimeException('STRIPE_SECRET is not set');| Setting (production) | Why |
|---|---|
display_errors = Off, log_errors = On |
Never show stack traces or paths to visitors |
expose_php = Off |
Don't advertise the PHP version |
session.cookie_secure = 1, session.cookie_httponly = 1, session.cookie_samesite = Lax |
Protect the session cookie |
| HTTPS everywhere | Encrypts passwords and cookies in transit (free certificates from Let's Encrypt) |
| Keep PHP and Composer packages updated | composer audit lists packages with known vulnerabilities |
Good randomness
Use random_bytes and random_int for anything security-related (tokens, reset codes); rand and mt_rand are predictable. Compare secrets with hash_equals, which takes the same time whether they match or not.
Checklist
| Threat | Defence |
|---|---|
| XSS | Escape all output (htmlspecialchars, auto-escaping templates) |
| SQL injection | Prepared statements; allow-lists for column names |
| Weak passwords storage | password_hash / password_verify |
| CSRF | Tokens in forms, SameSite cookies |
| Bad input | Validate on the server with allow-lists |
| Path traversal / uploads | Generate names, basename, store outside the web root |
| Leaked secrets | Environment variables, never in Git |
| Session theft | HTTPS, httponly/secure cookies, session_regenerate_id after login |
| Known vulnerabilities | Update PHP and dependencies (composer audit) |
Practice
- Write a comment form that saves comments to an array and prints them safely escaped. Try submitting
<b>bold</b>and a<script>. - Add a CSRF token to a form and reject submissions without the right token.
- Write
register()andlogin()functions that store apassword_hashand check it withpassword_verify. - Run
composer auditin one of your projects.
1.What stops a comment containing <script> from running in other users' browsers?
2.Which function should store passwords?
3.What does a CSRF token protect against?
4.Which function generates a secure random token?