Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 147 ยท Security

Secure Coding Checklist

Close the PHP security holes beyond XSS and SQL injection - file inclusion, path traversal, command injection, unserialize, open redirects and production config.

The earlier lessons in this chapter covered the attacks everyone talks about: XSS, CSRF, SQL injection and weak password storage. This lesson collects the rest: the smaller, quieter holes that still show up in real PHP applications every year. Each one has the same root cause you met in Web Security Basics: data from outside the trust boundary reaches a powerful function without being checked.

You'll look at six areas: including files based on user input, reading files by user-supplied path, running shell commands, unserializing data, redirecting to user-supplied URLs, and configuring PHP for production. For each, you'll see the vulnerable pattern, run it safely in the editor, and then fix it. The lesson ends with a checklist you can use when you review your own code.

All attacks in this lesson run inside our sandbox against throwaway files and fake data. They're here so you can recognize the patterns. Never test them against systems you don't own.

File inclusion: never include user input

include and require don't just read a file, they execute it as PHP. So the classic template-picker pattern is dangerous:

PHP
<?php
// DANGEROUS: ?page=../../../../etc/passwd or ?page=uploads/shell
include __DIR__ . '/pages/' . $_GET['page'] . '.php';

This is called local file inclusion (LFI). An attacker can climb out of pages/ with ../ and include any file the PHP process can read. If they can also get a file onto the server (an "image" upload that really contains PHP code, or a log file they've written into), including it runs their code. In old PHP setups with allow_url_include=On, they could even include a file from their own server (remote file inclusion). That setting has been off by default since PHP 5.2 and is deprecated as of PHP 7.4; leave it off.

The fix is not to clean the string. The fix is to never let input pick a file at all. Map allowed values to files you choose:

PHP A whitelist for included pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows that anything outside the list falls through to 404 Not Found, including home.php, which is close to a valid key but isn't one. Exact matching is the point: there is nothing to bypass. If you have many pages, a router does the same thing with a table of routes.

Path traversal: keep file reads inside a folder

Downloads, image resizers and "view attachment" features often take a file name from the URL. Even without include, a raw path lets attackers read files you never meant to serve, such as .env with your database password:

PHP
<?php
// DANGEROUS: ?file=../.env
readfile(__DIR__ . '/storage/invoices/' . $_GET['file']);

Checking for .. with str_contains() is a weak defense. Encodings, absolute paths, symbolic links and Windows backslashes all give attackers other routes. A sturdier approach has two layers:

  1. Validate the name against a strict pattern (for example letters, digits, dashes and one extension), or better, look the file up by an ID in your database and use the stored name.
  2. Resolve and confine: turn the final path into a canonical absolute path with realpath(), then check that it still starts with the allowed folder plus a directory separator.
PHP Confining reads to one folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The naive version happily prints DB_PASSWORD=hunter2. The safe version rejects ../.env at the first gate, and even if the pattern were sloppier, the realpath() prefix check would catch any path that ends up outside invoices/. Note the DIRECTORY_SEPARATOR in the check: without it, a folder named invoices-old would also pass a plain str_starts_with($path, $base) test.

basename() is a handy quick fix too: basename('../../.env') is .env, which strips the directories. It's fine as an extra layer, but on its own it still lets users open any file in the folder, so combine it with a pattern or an ID lookup. See Files and Directories for realpath() and friends.

Keep files that users upload or download outside the web root (the public/ folder your web server serves). Then even a mistake in your code can't turn into a direct URL to a private file. File Uploads covers this in detail.

Command injection: avoid the shell

Functions like exec(), shell_exec(), system(), passthru(), the backtick operator and popen() pass a string to the system shell (/bin/sh on Linux). The shell treats characters such as ;, |, &, $( ) and backticks as instructions. If user input lands in that string, the user can append commands of their own.

The editor below runs real shell commands in our sandbox. The "attack" only runs a second harmless echo, which is enough to prove the point:

PHP Command injection and escapeshellarg

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the unsafe run, the shell sees two commands separated by ;, so INJECTED is printed on its own line. With escapeshellarg(), the whole value becomes one quoted argument and the semicolon is just text.

The rules for shell commands, in order of preference:

  1. Don't shell out. PHP has built-in functions for most things people use the shell for: mkdir(), copy(), unlink(), ZipArchive, gd for images, hash_file() instead of sha256sum.
  2. Pass an array to proc_open() (PHP 7.4+). With an array of arguments, PHP starts the program directly, with no shell in between, so there's nothing to inject into.
  3. If you must build a string, wrap every variable argument in escapeshellarg(). escapeshellcmd() is not a substitute: it escapes metacharacters but still lets attackers add extra arguments.
  4. Validate anyway. If a value should be an integer or one of three formats, check that first.
PHP Running a program without a shell

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The program receives the whole string as a single argument, semicolon and all, and nothing else runs. Watch out for argument injection even here: if a user value starts with -, many programs read it as an option. Put a -- before user arguments where the program supports it, or validate that values don't start with a dash.

unserialize(): never on untrusted data

serialize() turns any PHP value, including objects, into a string, and unserialize() rebuilds it. That's the problem: a serialized string can name any class in your application, and rebuilding an object can trigger its magic methods, such as __wakeup(), __unserialize() and, later, __destruct(). Attackers chain these methods across classes in your code and your Composer packages (a so-called "POP chain") to delete files or run code. This is PHP object injection.

PHP Object injection through unserialize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the first case, merely unserializing and then discarding the value runs the destructor with a path the attacker chose. The string format is simple (O:8:"TempFile" means "an object of the 8-character class name TempFile"), so writing one by hand takes seconds. With ['allowed_classes' => false], PHP builds a harmless __PHP_Incomplete_Class instead, and no code from TempFile runs.

The rule: use JSON for data that crosses a trust boundary (cookies, form fields, API payloads, caches other systems can write to). JSON only produces arrays, strings, numbers, booleans and null. Keep serialize() for data only your own server writes and reads, and if you ever must unserialize something less trusted, pass allowed_classes. JSON and Comparing, Copying and Serializing Objects cover both formats.

Open redirects: check where you send people

A login page that supports ?return=/cart is convenient. Without a check, it's also an open redirect: ?return=https://evil.example/login sends your users, straight from your trusted domain, to a phishing page. Attackers love these because the link they share starts with your real domain.

Only allow local paths, and be careful: //evil.example is a protocol-relative URL that browsers treat as a different host, and some browsers treat a backslash like a slash.

PHP Accepting only local redirect targets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Everything that isn't a plain local path falls back to /. Rejecting control characters also blocks attempts to smuggle a line break into the Location header (modern PHP refuses multi-line headers anyway, but there's no reason to rely on that). If you need to redirect to other domains, compare the host from parse_url() against an explicit allow-list of hosts. HTTP Headers and Redirects shows the header('Location: ...') call that uses the result.

Production configuration

Many leaks come from configuration rather than code. These php.ini settings belong on every production server:

INI
; Show errors to developers in logs, never to visitors
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/log/php/error.log
error_reporting = E_ALL

; Don't advertise the PHP version in an X-Powered-By header
expose_php = Off

; Never include code from URLs
allow_url_include = Off

; Session cookies: HTTPS only, hidden from JavaScript, sent same-site only
session.cookie_secure = On
session.cookie_httponly = On
session.cookie_samesite = Lax
session.use_strict_mode = 1

; Optional hardening: limit which folders PHP may open
open_basedir = /var/www/app:/tmp

With display_errors on, an exception can print file paths, SQL queries and sometimes credentials into the page. Log them instead, as Errors, Warnings and Notices explains. Some teams also disable exec, shell_exec, system, passthru, proc_open and popen with disable_functions when the application never needs them.

You can inspect the active values with ini_get(). In our editor you're running the command-line PHP, so the results describe the sandbox, not a web server:

PHP A quick configuration audit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Our sandbox is a learning environment, not a production server: it shows errors on purpose so you can learn from them, so display_errors, log_errors and expose_php are all flagged. On your server, a script like this in a deploy check can catch a bad php.ini before customers do. Deploying PHP Applications covers production settings in more depth.

Dependencies and updates

Most of the code in a modern PHP app comes from Composer packages, and their vulnerabilities are yours. Keep them current:

Terminal
# Lists known security advisories for the packages in composer.lock
composer audit

# Shows which packages have newer versions
composer outdated --direct

Run composer audit in your CI pipeline so a vulnerable package fails the build. Also keep PHP itself on a supported version: each release gets two years of bug fixes and two more of security fixes, after which holes stay open forever. See Autoloading and Composer for how the lock file works.

The checklist

Use this list when you review a pull request or audit an old project:

Area Ask yourself
Output Is every value escaped for its context (XSS)?
SQL Is every query a prepared statement, with identifiers from a whitelist?
Forms Does every state-changing request check a CSRF token?
Passwords password_hash() and password_verify(), nothing else?
Includes Does any include/require path contain input? (It must not.)
File paths Are user-chosen paths validated, resolved with realpath() and confined?
Uploads Checked with finfo, renamed, stored outside the web root?
Shell Can you avoid the shell? If not, array proc_open() or escapeshellarg() on every argument?
Deserialization JSON for untrusted data; allowed_classes if unserialize() is unavoidable?
Redirects Only local paths or allow-listed hosts?
Sessions session_regenerate_id(true) on login, secure cookie flags?
Errors display_errors=Off, errors logged, generic error pages?
Secrets Credentials in environment variables or files outside the repo, never committed?
Dependencies composer audit clean, PHP version supported?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is include "pages/" . $_GET["page"] . ".php"; dangerous even if the pages folder only contains safe files?

    Path segments like ../ climb out of the folder, and include executes whatever it loads. Map allowed keys to file names instead of building paths from input.
  2. 2. A download script checks str_starts_with(realpath($path), realpath($base)). Which folder name could slip past this check?

    Without appending DIRECTORY_SEPARATOR to the base path, /data/invoices-old/x also starts with /data/invoices. Compare against the base plus a separator.
  3. 3. What is the safest way to run an external program with a user-supplied file name?

    With an array, proc_open() starts the program directly without a shell, so shell metacharacters mean nothing. Validation still guards against argument injection such as values starting with a dash.
  4. 4. What does unserialize($data, ['allowed_classes' => false]) do with a serialized object?

    With allowed_classes false, objects become __PHP_Incomplete_Class instances, which have no behavior. For data from outside, JSON is still the better choice.
  5. 5. Which return target should a safe login redirect reject?

    A value starting with // is a protocol-relative URL, so browsers send the user to another host. Only plain local paths should be accepted.

Summary

  • Never build include/require paths from input. Map allowed keys to files with match or a routing table.
  • For user-chosen files, validate the name, resolve it with realpath() and confirm it's inside the allowed folder (base path plus DIRECTORY_SEPARATOR). Store private files outside the web root.
  • Avoid the shell. Prefer built-in functions, then proc_open() with an array, and only as a last resort escapeshellarg() on every argument. escapeshellcmd() is not enough.
  • Don't unserialize() untrusted data: use JSON, or at least ['allowed_classes' => false].
  • Accept only local redirect targets (starting with one /, no //, no backslashes, no control characters) or allow-listed hosts.
  • In production: display_errors=Off, log_errors=On, expose_php=Off, allow_url_include=Off, secure session cookie flags.
  • Run composer audit, update dependencies and stay on a supported PHP version.

Next: Generators