Custom PHP

PHP Security Best Practices I Use in Production

PHP security best practices are the concrete habits that keep a PHP application from being turned against its own users: prepared statements for every query, context-aware output encoding, CSRF tokens on state-changing requests, hardened session cookies, and dependencies patched on a schedule. In my custom PHP builds these are defaults, not add-ons — applied from the first file and verified before launch.

By Saif Al Jahanwebdev-saif.com

Stop SQL injection at the query boundary

SQL injection is still the fastest way to lose a database, and it starts the moment a request value is concatenated into a query string. I open every PDO connection with PDO::ATTR_EMULATE_PREPARES set to false and PDO::ATTR_ERRMODE set to PDO::ERRMODE_EXCEPTION, then bind values through named placeholders like :id with bindValue() or execute(). Placeholders protect values only: a table or column name taken from a request must be matched against a fixed allowlist before it reaches the query. In WordPress builds the equivalent is $wpdb->prepare() with %s, %d and %f for every variable. Failed queries should raise exceptions that land in logs, never on screen.

  • One PDO connection with PDO::ATTR_EMULATE_PREPARES set to false
  • Named placeholders such as :id, bound with bindValue() or execute()
  • Whitelist dynamic column and table names; placeholders only cover values
  • In WordPress, use $wpdb->prepare() with %s, %d and %f
  • PDO::ERRMODE_EXCEPTION so failed queries surface in logs

Encode on output, not on input

Escaping on input corrupts data and still leaves holes, because the correct encoding depends on where the value lands. I store raw, trusted text in the database and encode at the output boundary: htmlspecialchars() with ENT_QUOTES | ENT_SUBSTITUTE and UTF-8 for HTML text and attributes, rawurlencode() for URL parts, and a strict JSON content type for API responses. Script, style and URL contexts each need their own rules, so a single generic escape function is not enough. In WordPress I use esc_html(), esc_attr(), esc_url() and wp_kses_post() for the small set of fields that legitimately allow markup. Twig and Blade autoescape by default; I treat any raw filter as a review flag.

  • htmlspecialchars() with ENT_QUOTES | ENT_SUBSTITUTE and UTF-8
  • Separate rules for HTML body, attribute, URL, JS and CSS contexts
  • esc_html(), esc_attr(), esc_url() and wp_kses_post() in WordPress
  • Treat raw or unescaped output filters as a code-review flag
  • Store raw text in the database; encode only when rendering

Require a CSRF token on every state-changing request

A CSRF token makes a state-changing request prove it came from a page my application rendered. I generate one with bin2hex(random_bytes(32)), keep it in the session, include it as a hidden field or header on every POST, PUT and DELETE, and compare it with hash_equals() so the check is timing-safe. A mismatch returns 403 and writes nothing. Tokens can be per-session or per-form; per-form is stricter and worth the extra state for payment and account changes. SameSite=Lax on the session cookie is useful defence in depth, not a replacement, because it does not cover every top-level navigation. In WordPress I pair wp_nonce_field() with check_admin_referer(), and I treat a nonce as CSRF protection rather than authentication.

  • bin2hex(random_bytes(32)) generated and stored in the session
  • hash_equals() for a timing-safe comparison on every check
  • Apply to POST, PUT, PATCH and DELETE, not just the login form
  • SameSite=Lax as defence in depth, never the only control
  • wp_nonce_field() paired with check_admin_referer() in WordPress

Harden the session cookie and its lifecycle

Session cookies are bearer credentials, so the cookie attributes matter as much as the login logic. I set httponly to true so JavaScript cannot read the token, secure to true so it never travels over plain HTTP, and samesite to Lax or Strict depending on whether external links need to land authenticated. session.use_only_cookies is on and session.use_strict_mode rejects IDs the server did not issue, which blocks common fixation attempts. I call session_regenerate_id(true) after login and any privilege change, track an idle timeout of around 30 minutes for administrative screens, and destroy the session fully on logout. Absolute lifetime and garbage-collection settings stay explicit rather than relying on defaults.

  • httponly=true, secure=true, samesite=Lax or Strict
  • session.use_only_cookies=1 and session.use_strict_mode=1
  • session_regenerate_id(true) on login and privilege changes
  • Explicit idle timeout and session.gc_maxlifetime
  • session_destroy() plus cookie expiry on logout

Keep dependencies and the runtime patched on a schedule

Most PHP breaches are not exotic; they are a known vulnerability in a package nobody upgraded. I keep composer.lock committed, run composer audit in CI, and review composer outdated --direct on a fixed cadence rather than whenever a breach makes news. Updates land on a staging branch first, then go live with the lock file, not a fresh unconstrained resolve. Any package that is abandoned or has not seen a release in years gets replaced or vendored under our own review. The same rule covers the runtime: I track the supported PHP branch and move off end-of-life versions before the security window closes. For WordPress sites that means core, plugins and themes on the same schedule.

  • composer audit in CI on every pull request
  • Commit composer.lock and deploy from the lock file
  • composer outdated --direct reviewed at least monthly
  • Retire abandoned packages and end-of-life PHP versions
  • Stage core, plugin and theme updates before production

Verify the controls before you ship

Controls only count when someone verifies them. My review pass starts with a grep for raw $_GET, $_POST and $_REQUEST reaching a query or template, then checks uploads with finfo_file() and a hardcoded extension allowlist rather than trusting the filename or MIME header. Production runs with display_errors off and errors logged to a protected file, a database user with only the grants it needs, HTTPS with HSTS, and no eval() or unserialize() on request data. I'm Saif Al Jahan, a freelance WordPress and PHP developer in Mymensingh, Bangladesh; the checklists on webdev-saif.com are the same ones I apply to custom PHP and WooCommerce builds. Readiness is a short, repeatable pass — not a one-off audit the week before launch.

  • Grep for raw request superglobals reaching SQL or templates
  • Validate uploads with finfo_file() and a fixed extension allowlist
  • display_errors off in production; errors logged to a protected file
  • Least-privilege database user and HTTPS with HSTS
  • No eval(), shell execution or unserialize() on request data

Frequently asked questions

What are the essential PHP security best practices for a small app?

Five controls cover most of the risk: prepared statements for every database query, context-aware output encoding, CSRF tokens on all state-changing requests, session cookies set with httponly, secure and samesite, and a scheduled dependency update routine. Add HTTPS, production error logging and a least-privilege database user, and you have a baseline that scales from a single PHP file to a large application.

Are prepared statements enough to prevent SQL injection?

They prevent injection through values when you use real, non-emulated prepares with PDO and bind every variable. They do not protect identifiers such as table or column names, so those must come from a fixed allowlist. You also still need to validate input types and keep the database account minimally privileged. Prepared statements are one control, not the whole defence.

Should I sanitize input or escape output?

Escape output. Validation at input is useful for shape and type — an integer ID should be an integer — but the encoding that matters depends on where the value is rendered. HTML text, an attribute, a URL and a JSON field each need different treatment. Store the original value and apply the right encoder at the point of output.

Do SameSite cookies replace CSRF tokens?

No. SameSite=Lax blocks many cross-site POSTs, but it is not consistently enforced across every browser, subdomain and top-level navigation. Keep an explicit token checked with hash_equals() on POST, PUT and DELETE, and treat SameSite as a second layer. In WordPress, wp_nonce_field() and check_admin_referer() remain necessary even with hardened session cookies.

How often should I update PHP dependencies?

Run composer audit on every pull request and review composer outdated --direct at least monthly. Apply patches to a staging branch, deploy from the committed composer.lock, and replace packages that are abandoned or unsupported. Track the PHP runtime the same way; staying on an end-of-life branch removes your access to security fixes regardless of how clean your application code is.

Written by Saif Al Jahan, webdev-saif.com · Mymensingh, Bangladesh. Last updated .