You're seeing Seahawk's original 2015 colors and logo. Thousands of WordPress sites maintained since.

Book a call Free rebuild
Home/Security/PHP Security: A Practical Guide to Securing PHP Applications
Guide

PHP Security: A Practical Guide to Securing PHP Applications

Published November 21, 2026 10 min read

PHP runs a large share of the web, from custom business applications and APIs to WordPress, Laravel, and Symfony sites. Modern PHP gives you solid built-in tools for writing secure code: prepared statements, a password hashing API, strict session handling, and a type system that catches mistakes early. Most PHP security incidents come not from the language but from how an application uses it and how the server is configured.

This guide covers the practical side of PHP security: running a supported PHP version, validating input and escaping output, prepared statements, password hashing, session and cookie settings, safe file uploads, keeping Composer dependencies current, and the php.ini settings that harden a server. The last section explains how PHP upgrades fit into routine care for WordPress sites.

1. Run a supported PHP version

Every PHP release branch gets a period of active support, with bug and security fixes, followed by a period of security fixes only. After that it reaches end of life and the PHP project stops releasing fixes for it, including for newly discovered vulnerabilities. The current status of every branch is on the PHP supported versions page. Check it rather than relying on memory, because the dates move each year.

  • Know what you run. Run php -v on the server, or check your hosting control panel. On WordPress, Tools, Site Health, Info shows the PHP version under Server.
  • Stay on a branch that receives security fixes, and apply minor releases within the branch promptly. Minor releases are where security fixes land.
  • Plan the next major upgrade before your branch reaches end of life. Upgrading under deadline pressure is where things break. Read the migration notes in the PHP manual appendices for each version you are moving through.

If you rely on an operating system vendor that backports security fixes into an older PHP package, confirm that coverage for your exact version. Without it, an end-of-life PHP version is a known risk that grows every month.

2. Validate input and escape output

Treat everything that comes from outside your code as untrusted: form fields, query strings, cookies, headers, uploaded files, API responses, and data you stored earlier from any of those. Two separate habits handle it.

Validate on the way in

Check that each value is what you expect before you use it. Use filter_var with FILTER_VALIDATE_INT, FILTER_VALIDATE_EMAIL, or FILTER_VALIDATE_URL for common types, declare strict types and typed parameters so wrong types fail loudly, and use allowlists for anything with a fixed set of valid values, such as a sort order or a country code. Reject invalid input rather than trying to repair it.

Escape on the way out

Escape data at the moment you output it, for the context it is going into. For HTML, use htmlspecialchars with ENT_QUOTES and UTF-8, or your template engine's auto-escaping (Twig and Blade escape by default). Attributes, URLs, JavaScript, and CSS each need their own escaping, so do not reuse HTML escaping everywhere. This is the main defense against cross-site scripting, which the OWASP Top 10 groups under injection.

Protect state-changing requests

Any form or request that changes data should carry a CSRF token tied to the user's session, checked on the server before the action runs. Frameworks such as Laravel and Symfony include this; in plain PHP, generate a token with random_bytes, store it in the session, and compare it with hash_equals.

3. Use prepared statements for every query

SQL injection happens when user input is joined into a query string. Prepared statements keep the query and the data separate, so input can never change the query's structure. With PDO, write the query with placeholders, call prepare, then pass the values to execute. The PHP manual on prepared statements shows the pattern for both named and positional placeholders. MySQLi supports the same approach.

  • Use placeholders for every value, including ones you think are safe, such as IDs from your own database.
  • Placeholders cannot stand in for table or column names. When those come from input (a sortable table, for example), map the input to an allowlist of known names.
  • Set PDO to throw exceptions on errors, and never show raw database errors to visitors.
  • Give the application's database user only the privileges it needs. A site that never alters its schema does not need DROP or ALTER rights in production.

4. Hash passwords with the built-in API

Never store passwords in plain text, and never use fast general-purpose hashes such as MD5 or SHA-1 for them. PHP's password API does the hard parts for you: password_hash creates a salted hash with a deliberately slow algorithm, and password_verify checks a login attempt against it.

  • Use PASSWORD_DEFAULT so your code moves to stronger algorithms as PHP adopts them, and store hashes in a column that allows at least 255 characters, as the manual recommends.
  • Call password_needs_rehash after a successful login and save a new hash if it returns true. Old hashes upgrade themselves over time.
  • Rate-limit login attempts and offer two-factor authentication for administrator accounts.
  • Keep secrets such as database passwords and API keys out of your code repository. Load them from environment variables or a configuration file outside the web root.

5. Harden sessions and cookies

A stolen session cookie lets an attacker act as the user without a password. These settings, set in php.ini or before session_start, close the common gaps. The PHP manual's session security page explains each one.

SettingValueWhy
session.use_strict_mode1Rejects session IDs the server did not create, which blocks session fixation
session.use_only_cookies1Keeps session IDs out of URLs, where they leak through logs and referrers
session.cookie_httponly1Stops JavaScript from reading the session cookie
session.cookie_secure1Sends the cookie only over HTTPS
session.cookie_samesiteLax or StrictLimits when the browser sends the cookie on requests from other sites

Call session_regenerate_id(true) whenever a user logs in or changes privilege level, and destroy the session fully on logout. Apply the same HttpOnly, Secure, and SameSite options to any other cookie you set with setcookie.

6. Handle file uploads safely

Upload forms are a favorite way to get a malicious PHP file onto a server. Treat every upload as hostile until checked:

  • Check the upload's error code and size first, and set upload_max_filesize and post_max_size to what the application actually needs.
  • Detect the file type from its contents with the finfo functions. Do not trust the browser-supplied MIME type or the file name's extension.
  • Allow only the types you need, and choose the stored file's extension yourself based on the detected type.
  • Rename every file to a random name and move it with move_uploaded_file.
  • Store uploads outside the web root, or in a directory where the web server will not execute PHP. Serve them through a script that checks permissions if they are private.
  • For images, re-encoding the file strips anything hidden in it and normalizes the format.

7. Keep Composer dependencies up to date

Most modern PHP applications are mostly other people's code: frameworks, libraries, and SDKs pulled in by Composer. A vulnerability in any of them is a vulnerability in your application.

  • Commit composer.lock so every environment installs the exact versions you tested.
  • Run composer audit regularly, and in your CI pipeline, to check installed packages against known security advisories.
  • Run composer outdated to see what has fallen behind, and update in small steps rather than one large jump a year.
  • Install with --no-dev in production so testing and debugging tools never reach the live server.
  • Remove packages you no longer use, and prefer well-maintained libraries with recent releases.

8. Harden the server configuration

Good code on a loosely configured server is still exposed. Review php.ini (and each PHP-FPM pool) for these settings:

SettingRecommendedWhy
display_errorsOff in productionError messages reveal file paths, queries, and code to visitors
log_errorsOnKeeps errors in a log you can read, instead of on the page
expose_phpOffRemoves the PHP version from response headers
allow_url_includeOffStops include and require from loading remote code
disable_functionsFunctions the app never uses, such as exec, shell_exec, system, passthru, proc_open, and popenLimits what an attacker can do if they get code running. It can only be set in php.ini, so test first: some backup and image tools rely on these functions
open_basedirThe site's own directory plus its temp and upload pathsRestricts which directories PHP can open files in. Treat it as a safety net, not a replacement for file permissions and separate accounts
file_uploadsOff if the application never accepts uploadsRemoves an attack surface you do not need

Beyond php.ini, run each site under its own system user and PHP-FPM pool so a compromise on one site cannot read another, keep file permissions tight (code should not be writable by the web server unless it must be), serve everything over HTTPS, and keep the web server and operating system patched.

9. Log, monitor, and test

Security is a routine, not a launch task. Log failed logins and unexpected errors, and review the logs. Monitor for file changes in directories that should not change. Run a static analysis tool such as PHPStan or Psalm in CI to catch unsafe patterns, and schedule a security review or penetration test after major changes to authentication, payments, or file handling.

PHP security for WordPress sites

WordPress is a PHP application, so everything above applies, plus a few WordPress-specific habits. Theme and plugin developers should use $wpdb->prepare for queries, the escaping functions (esc_html, esc_attr, esc_url, wp_kses) for output, the sanitize functions for input, nonces for forms, and current_user_can checks before any privileged action. Site owners mostly need to keep three things current: WordPress core, plugins and themes, and the PHP version underneath them.

The PHP version is the one that gets forgotten, because it lives at the host and an upgrade can break older plugins or custom theme code. The safe way to do it:

  1. Check your current version in Site Health, and compare it with the WordPress requirements page and php.net's supported versions table.
  2. Update WordPress core, plugins, and themes first, since current releases are the most likely to support current PHP.
  3. Copy the site to staging, switch staging to the new PHP version, and test key pages, forms, checkout, and the admin with error logging on.
  4. Fix or replace anything that throws errors, then switch the live site and watch the error log for a few days.

If you would rather not manage this yourself, PHP upgrades are part of our WordPress care plans. Every WP Care plan includes PHP monitoring. WP Care Pro, from $99 a month, adds the PHP upgrade itself, which covers the code fixes needed to reach current PHP; a site whose code is too old to patch needs a rebuild, which we quote before any work starts. A one-off PHP upgrade outside a plan is $299. Our WordPress security services cover the rest of the routine: malware scans, virtual patching, tested updates, and backups. If a site has already been compromised, follow our guide to fixing a hacked WordPress site.

Getting help with PHP security

For custom PHP and Laravel applications, Seahawk's engineers handle upgrades to current PHP releases, security patching, code reviews, and dependency updates through our PHP development services. SeaPHP, Seahawk's practice for mission-critical PHP services, is currently in early access.

Frequently asked questions

Is PHP secure?

Yes, when it is kept up to date and used well. Current PHP versions include prepared statements, a strong password hashing API, strict session settings, and type checks that make secure code straightforward to write. Most PHP security problems come from application code that skips these tools, outdated dependencies, an end-of-life PHP version, or a loosely configured server.

How do I know if my PHP version is still supported?

Check your version with php -v, your hosting control panel, or Tools, Site Health in WordPress, then compare it with the supported versions table on php.net. A branch in active support gets bug and security fixes; one in security support gets only security fixes; an end-of-life branch gets nothing, so plan the upgrade before you reach that point.

What are the most common PHP security vulnerabilities?

SQL injection from queries built with user input, cross-site scripting from unescaped output, cross-site request forgery on forms without tokens, insecure file uploads that let PHP files onto the server, weak password storage, session hijacking, and known vulnerabilities in outdated Composer packages or plugins. Prepared statements, escaping, CSRF tokens, upload checks, and regular updates prevent most of them.

Should I turn off display_errors in production?

Yes. With display_errors on, PHP prints warnings and errors on the page, which can reveal file paths, database queries, and code to anyone who triggers them. Set display_errors to Off and log_errors to On in production, and read the error log instead. Keep display_errors on only in local development.

Will upgrading PHP break my WordPress site?

It can if a plugin, theme, or custom code relies on behavior that changed. That is why you update everything first, test the new PHP version on a staging copy, fix what throws errors, and only then switch the live site. Most well-maintained plugins support current PHP. Old custom code is the usual source of problems.

Does WP Care include PHP upgrades?

WP Care includes PHP monitoring. The PHP upgrade itself is included from WP Care Pro, at $99 a month, and covers the code fixes needed to reach current PHP. A site whose code is too old to patch needs a rebuild, quoted before any work starts. Without a plan, a one-off PHP upgrade is $299.

Pro Services

White-label WordPress, PHP, EmDash, and Astro services for web hosts.

Launch pro services under your brand and become a results-driven technology partner to your customers. Activate, retain, and expand repeatable, premium recurring revenue across your existing base.