PHP Security Best Practices: A 2026 Checklist for PDO, Passwords, Sessions, Uploads and php.ini

A practical PHP security checklist with code you can paste: PDO prepared statements, password_hash and rehashing, output escaping, CSRF tokens with hash_equals, hardened session settings, safe file uploads, composer audit in CI and a production php.ini, each tied to the PHP manual or OWASP.

Cover for the article PHP Security Best Practices: A 2026 Checklist for PDO, Passwords, Sessions, Uploads and php.ini

Most PHP security problems come from nine habits: running an unpatched version, building SQL from strings, storing passwords badly, printing user input unescaped, accepting cross-site form posts, loose session settings, trusting uploaded files, ignoring vulnerable dependencies and leaving a development php.ini in production. This checklist covers each one with code that works on PHP 8.2 to 8.5, and each claim comes from the PHP manual, the Composer docs or the OWASP cheat sheets. It is aimed at developers who maintain or inherit a PHP site, such as the legacy admin or marketing site that sits next to a Node.js and Angular project.

Here is the list. The rest of the post explains each item.

  1. Run a supported PHP branch on its latest patch release.
  2. Use PDO prepared statements for every value, and an allowlist for column and table names.
  3. Hash passwords with password_hash(), check with password_verify(), upgrade with password_needs_rehash().
  4. Escape output for its context, with htmlspecialchars() for HTML.
  5. Protect state-changing requests with a CSRF token, and use SameSite cookies as a second layer.
  6. Set the session ini settings, and regenerate the session ID on login.
  7. Treat every upload as hostile: check the error code, size and content, rename the file and store it outside the web root.
  8. Run composer audit on every build.
  9. Harden php.ini and keep errors out of responses.

1. Run a supported version, fully patched

Everything below is weakened by an engine bug. The OWASP PHP configuration cheat sheet includes this item: run a branch that is listed on php.net's supported versions page, and plan the upgrade before its security support ends. On 5 November 2026 that means 8.5, 8.4, 8.3 or 8.2, with 8.2 ending on 31 December 2026. The October 2026 release fixed two critical remote code execution bugs, so read PHP vulnerabilities in 2026 first if you have not patched.

2. SQL injection: prepared statements with PDO

The PHP manual is direct about this: if an application exclusively uses prepared statements, the developer can be sure no SQL injection will occur, with one caveat. If other parts of the query are built from unescaped input, injection is still possible. Placeholders stand in for whole values, so they cannot hold a column name, a table name or a sort direction, and a LIKE wildcard belongs in the bound value, not in the SQL string.

One detail worth knowing: the manual states that PDO_MYSQL uses emulated prepares by default, meaning PDO builds the final SQL on the client. I turn emulation off so the server prepares the statement and values travel separately, and I set the character set in the DSN.

<?php
$pdo = new PDO(
    'mysql:host=localhost;dbname=shop;charset=utf8mb4',
    $user,
    $pass,
    [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES   => false,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]
);

$stmt = $pdo->prepare('SELECT id, email FROM users WHERE email = :email AND status = :status');
$stmt->execute([':email' => $email, ':status' => 'active']);
$user = $stmt->fetch();

// LIKE: the wildcards go into the value, not into the SQL
$stmt = $pdo->prepare('SELECT id FROM products WHERE name LIKE ?');
$stmt->execute(['%' . $term . '%']);

For identifiers, map user input to a fixed list and never concatenate the raw value:

<?php
$sortable = ['name' => 'name', 'price' => 'price', 'newest' => 'created_at'];
$column = $sortable[$_GET['sort'] ?? ''] ?? 'created_at';   // unknown input falls back
$sql = 'SELECT id, name FROM products ORDER BY ' . $column . ' DESC';

3. Passwords: password_hash, password_verify, password_needs_rehash

Never write your own hashing scheme and never use a fast hash such as MD5 or SHA-1 for passwords. password_hash() chooses a salt for you, and its output contains the algorithm and cost, so password_verify() needs nothing else. The manual recommends a column that can grow beyond 60 bytes, and suggests 255, because PASSWORD_DEFAULT is designed to change over time. It uses bcrypt today, with a default cost of 12 since PHP 8.4 (it was 10 before). With bcrypt, the manual notes that the password is truncated to 72 bytes.

OWASP's password storage cheat sheet ranks Argon2id first, with a minimum of 19 MiB of memory, two iterations and one degree of parallelism, and treats bcrypt as a choice for legacy systems with a work factor of at least 10. PHP supports Argon2id with PASSWORD_ARGON2ID (added in 7.3) and the options memory_cost in kibibytes and time_cost. Whether the constant exists depends on how your PHP was built, so check for it. The manual's own pattern for upgrading hashes is to verify first, then rehash:

<?php
$algo = defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : PASSWORD_BCRYPT;
$options = $algo === PASSWORD_BCRYPT
    ? ['cost' => 12]
    : ['memory_cost' => 19456, 'time_cost' => 2];     // 19 MiB, 2 iterations

$hash = password_hash($password, $algo, $options);      // store in a VARCHAR(255)

if (password_verify($password, $row['password_hash'])) {
    if (password_needs_rehash($row['password_hash'], $algo, $options)) {
        $newHash = password_hash($password, $algo, $options);
        // UPDATE users SET password_hash = :hash WHERE id = :id
    }
    // sign the user in
}

Only the user's login request has the plain password, so rehashing has to happen there. Over a few months, every active account moves to the stronger setting without a forced reset.

4. Output escaping for XSS

Escape on output, at the point where you know the context. For HTML text and quoted attributes, use htmlspecialchars(). Since PHP 8.1 its default flags are ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, so single quotes are converted too, and invalid UTF-8 is replaced instead of producing an empty string. The manual still recommends passing the encoding explicitly, and a short wrapper keeps templates readable:

<?php
function e(?string $value): string
{
    return htmlspecialchars($value ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<h1><?= e($product['name']) ?></h1>
<a href="/search?q=<?= e(rawurlencode($query)) ?>">Search again</a>

HTML escaping does not make every context safe. A user-supplied URL needs its scheme checked against an allowlist (http and https) before it goes into an href, and data placed inside a script block needs JSON encoding, not HTML escaping. If you allow users to submit HTML, use a maintained sanitising library with an allowlist, not a regular expression.

5. CSRF: tokens first, SameSite second

The OWASP CSRF cheat sheet says stateful software should use the synchronizer token pattern: the server creates an unpredictable token, keeps it in the session and compares it with what the form sends back. SameSite cookies are described as useful defence in depth that does not replace a proper CSRF defence in most deployments, partly because Lax still sends the cookie on top-level GET navigations, so a state-changing action must never be reachable by GET. Use random_bytes(), which the manual says is suitable for all applications, including long-term secrets, and compare with hash_equals(), with the known secret as the first argument:

<?php
session_start();
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}
// In every form: <input type="hidden" name="csrf" value="<?= e($_SESSION['csrf']) ?>">

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sent = $_POST['csrf'] ?? '';
    if (!is_string($sent) || !hash_equals($_SESSION['csrf'], $sent)) {
        http_response_code(403);
        exit('Invalid CSRF token');
    }
}

For a JSON API called from JavaScript, OWASP also lists a custom request header (such as X-CSRF-Token) that the server requires, and Fetch Metadata headers with an origin check as a fallback. If you use a framework, check whether it already ships CSRF protection and that it is switched on before writing your own.

6. Sessions: ini settings and a new ID on login

The manual's session security page says session.use_strict_mode is mandatory for secure sessions and is disabled by default. It also recommends cookies only, httponly and secure on the session cookie, SameSite set to Lax or Strict, transparent session IDs off, and a save path that is not world-readable, such as /tmp:

; php.ini (or the FPM pool), applied before session_start()
session.use_strict_mode = 1
session.use_cookies = 1
session.use_only_cookies = 1
session.use_trans_sid = 0
session.cookie_httponly = 1
session.cookie_secure = 1          ; HTTPS only; consider HSTS too
session.cookie_samesite = "Lax"    ; or "Strict"
session.cookie_lifetime = 0
session.save_path = "/var/lib/php/sessions"   ; not world-readable

OWASP's session management cheat sheet adds two rules that PHP does not enforce for you. Renew the session ID after any privilege change, and enforce idle and absolute timeouts on the server. In PHP that means calling session_regenerate_id(true) right after a successful login, and storing a last-activity timestamp in the session. The manual warns that deleting the old session immediately can lose a session on an unstable mobile connection and removes your ability to detect reuse of a stolen ID, and it documents a pattern that stamps the old session as destroyed instead. If your app makes many parallel requests, follow that pattern.

7. File uploads

The manual's upload page is mostly user notes, but they agree on the points that matter, and they match the OWASP guidance. The browser-supplied type and name are not trustworthy, a hidden MAX_FILE_SIZE field is not a security control, and uploads should not be stored where the web server can execute them. move_uploaded_file() also checks that the source really is an upload, and it overwrites an existing destination, which is another reason to generate your own file name:

<?php
$file = $_FILES['avatar'] ?? null;
if (!$file || is_array($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
    throw new RuntimeException('Upload failed');
}
if ($file['size'] > 2_000_000) {
    throw new RuntimeException('File too large');   // your limit, not MAX_FILE_SIZE
}
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
$ext = $allowed[$mime] ?? null;
if ($ext === null) {
    throw new RuntimeException('Unsupported file type');
}
$name = bin2hex(random_bytes(16)) . '.' . $ext;     // never reuse the client's name
if (!move_uploaded_file($file['tmp_name'], '/var/app-uploads/' . $name)) {
    throw new RuntimeException('Could not store the file');
}

The content check with finfo reads the file's bytes, which is better than trusting the browser, but it is one check, not proof that a file is harmless. Store uploads outside the document root, or in a directory where PHP execution is disabled, and serve them with the type you decided on. Set upload_max_filesize and post_max_size in php.ini or the server configuration, not with ini_set(), because they cannot be changed at runtime.

8. Dependencies: composer audit

composer audit checks installed packages against the Packagist security advisories. Run it against the lockfile in CI so a vulnerable package fails the build: it exits with code 1 when a package matches an advisory, and 0 when it finds nothing. Useful options are --locked (audit composer.lock instead of vendor), --no-dev, --format and --abandoned=fail if you also want to stop on abandoned packages. Composer's configuration docs also list an audit option, block-insecure, that blocks package versions affected by advisories, though they mark that config section as deprecated in favour of config.policy, so check the docs for your Composer version before relying on it.

# .github/workflows/php.yml (excerpt)
- run: composer install --no-interaction --prefer-dist
- run: composer audit --locked --no-dev

9. Harden php.ini

The OWASP PHP configuration cheat sheet gives a production baseline. These are the settings I would apply first, taken from its tables:

SettingValueWhy
expose_phpOffStops advertising the PHP version
display_errors, display_startup_errorsOffErrors must not reach the browser in production
log_errors, error_logOn, a real pathErrors go to a log you review
error_reportingE_ALLLog everything
allow_url_includeOffKeeps a local file inclusion bug from becoming a remote one
allow_url_fopenOffBlocks remote URLs in file functions, if your code does not need them
enable_dlOffNo loading extensions at runtime
zend.exception_ignore_argsOnKeeps function arguments out of exception traces
open_basedirYour app directoryLimits which files PHP can touch

Three cautions from the same cheat sheet. Its example disable_functions list contains functions many applications need, including move_uploaded_file, putenv, mkdir and rename, so build your own list from what the app never calls instead of pasting it. Its "paranoid" section suggests memory_limit of 50M, but the October 2026 advisory for CVE-2026-109618 temporarily recommends the opposite, memory_limit=-1, as a stopgap, which is one more reason to patch instead. And allow_url_fopen=Off breaks code that reads remote files with file_get_contents(), so test before you deploy.

Errors and secrets

The PDO manual warns that an uncaught connection exception becomes a fatal error whose backtrace can leak connection details, which is why display_errors must be off. Catch the exception, log the message on the server and return a generic 503. Keep database passwords and API keys outside the web root, in environment variables or a file the web server cannot serve, and out of version control.

Short FAQ

Is htmlspecialchars() enough to prevent XSS?

For text and quoted attributes in HTML, yes, when you pass the right flags and encoding. It does not cover URLs, JavaScript contexts or user-supplied HTML, which need their own handling.

Do I still need CSRF tokens if my cookies are SameSite?

OWASP says SameSite is defence in depth and does not replace a CSRF defence in most deployments. Keep the token.

Is bcrypt still acceptable?

OWASP ranks it for legacy systems, with a work factor of at least 10. PHP 8.4's default cost of 12 meets that. Prefer Argon2id when your build supports it, and use password_needs_rehash() to migrate.

Where does a Node.js or MEAN project fit?

The same ideas apply with different tools: validated input, parameterised queries, httpOnly cookies and a patched runtime. My notes for the Node side are in Patching a MEAN Stack and protecting a Node.js project from npm supply-chain attacks.

Sources

All pages were checked on 5 November 2026.