Home / Guides / WordPress handbook / Chapter 06

WordPress handbook · Chapter 06 · Infrastructure

PHP, Server and Hosting Configuration

Performance and stability problems that look like "WordPress is slow" or "the site keeps crashing" are usually resource limits: memory, execution time, PHP workers, or the hosting model itself. This chapter explains each setting, what it does to WordPress, and how to change it on hosting where you may not have root access.

Updated · 15 min read · Level: Advanced

On this page
  1. PHP versions and compatibility
  2. PHP-FPM, workers and process limits
  3. PHP extensions WordPress uses
  4. PHP directives: what each setting does
  5. Memory exhaustion and why "just add more memory" fails
  6. Timeouts: why they occur and which layer timed out
  7. How inefficient plugins consume server resources
  8. Hosting models: shared, VPS, managed and dedicated
  9. Apache, Nginx and LiteSpeed compared
  10. Error reporting and PHP logs

PHP versions and compatibility

Each PHP release branch gets about two years of active support and then two years of security-only fixes before reaching end of life. After that, newly discovered vulnerabilities in PHP itself are not fixed. Newer versions are also substantially faster. WordPress 7.0 raised its absolute minimum to PHP 7.4 and recommends PHP 8.3 or newer; the WordPress Hosting Team's recommendation for new installations is the newest branches. Check php.net/supported-versions.php and the WordPress requirements page for the current position.

The practical constraint is rarely WordPress core; it is plugins and themes. Major PHP versions remove deprecated features and make previously tolerated mistakes into fatal errors (PHP 8.0 was particularly strict). Common upgrade breakages: "Uncaught TypeError", "Call to undefined function" (removed functions, or a missing extension), and floods of deprecation notices.

Upgrading PHP safely

  1. Check the current version in Tools → Site Health → Info → Server.
  2. Update all plugins and themes first; developers fix compatibility in new releases.
  3. Clone to staging and switch staging to the target version (most hosting panels offer a per-site PHP selector).
  4. Enable logging (WP_DEBUG_LOG to a private path) and exercise the site: front end, admin, forms, checkout, cron tasks, imports.
  5. Fix or replace anything that produces fatal errors or warnings. Deprecation notices are a to-do list for the next upgrade.
  6. Switch production at a quiet time, watch the error log, and keep the previous version available for a quick switch back.
Verify

Site Health shows the new version; the error log is quiet after a full test pass; cron and background jobs still run.

What could go wrong

Fatal errors from incompatible plugins; missing extensions on the new version (each version may have its own extension set).

Rollback

Select the previous version in the hosting panel. The change is immediate and does not touch files or data.

Escalate when

A business-critical plugin has no compatible version, or the host does not offer a supported PHP branch.

PHP-FPM, workers and process limits

PHP-FPM maintains a pool of worker processes per site or user. Each worker handles exactly one request at a time, from start to finish. Requests that need PHP queue when every worker is busy. The key pool settings:

DirectiveWhat it controlsEffect on WordPress
pmProcess manager mode: static (fixed number of workers), dynamic (scales between min and max spare), ondemand (spawns on demand, kills when idle)ondemand saves memory on low-traffic sites but adds latency on the first requests after idle; static gives predictable capacity on dedicated servers
pm.max_childrenMaximum simultaneous workersThe concurrency cap for uncached requests. "server reached pm.max_children setting" in the FPM log means requests queued.
pm.start_servers, pm.min_spare_servers, pm.max_spare_serversWorker counts for dynamic modeToo few spares cause spawn delays during bursts
pm.max_requestsRequests a worker serves before being recycledContains slow memory leaks in plugins; 500–1000 is common
request_terminate_timeoutHard kill for a single requestOverrides max_execution_time in some situations; too low kills imports and backups
request_slowlog_timeout + slowlogLogs a stack trace for requests slower than N secondsVery useful for finding which plugin function is slow

Sizing workers: why more is not always better

Each worker uses memory: typically 40–120 MB for WordPress, more for WooCommerce and page builders. A rough ceiling is:

max_children ≈ (RAM available to PHP) ÷ (average worker memory)
             ≈ (4096 MB total − 1024 MB for DB/OS/cache) ÷ 80 MB ≈ 38 workers

Setting max_children higher than memory allows makes the server swap or the kernel kill processes, which is worse than queuing. Throughput also depends on CPU: 40 workers on 2 CPU cores will mostly be waiting for CPU. On shared and managed hosting, worker counts are fixed by the plan; "PHP workers" is often the main difference between plan tiers.

Why PHP workers become exhausted

Workers run out when requests arrive faster than they finish. That happens either because there are more uncached requests, or because each request takes longer:

  • Uncacheable traffic: logged-in users, WooCommerce carts, admin-ajax.php calls (including the Heartbeat API every 15–60 seconds per open admin tab), search, REST requests, bots hitting random URLs.
  • Slow external calls: a plugin calling a licence server, an API or a font service during page generation. If that service takes 10 seconds to time out, every request holds a worker for 10 seconds. This is a common cause of sudden site-wide outages that "fix themselves".
  • Slow database queries: unindexed meta queries, huge autoloaded options, table locks during backups.
  • Heavy scheduled work: WP-Cron triggered by visitor requests runs imports, emails and clean-up inside a web worker.
  • Attacks: login brute force and XML-RPC floods are uncacheable by design.

Symptoms: response times climb, then 502/503/504 errors appear site-wide, often while CPU is not even at 100% (workers are waiting, not computing). Investigate with the FPM log (max_children warnings), the slow log, access logs for request patterns at the time, and Query Monitor or APM tools for slow components. Fix by making requests cacheable, removing slow external calls from page loads, moving cron to a system scheduler, blocking abusive traffic at the edge, and only then adding workers or upgrading the plan.

PHP extensions WordPress uses

ExtensionStatusUsed forIf missing
mysqliRequiredDatabase connection"Your PHP installation appears to be missing the MySQL extension"
jsonRequired (built-in in PHP 8)REST API, block editor, settingsFatal errors
curlHighly recommendedHTTP requests: updates, APIs, payment gatewaysSlower fallback transports; some gateways fail
opensslHighly recommendedHTTPS requests, signature checks for updatesUpdate and API failures
mbstringRecommendedMultibyte text handlingBroken non-ASCII text in some plugins
imagick or gdRecommended (one at least)Image resizing, thumbnails, WebP/AVIFNo thumbnails; image processing errors
exifRecommendedReading image orientation and metadataRotated photos
fileinfoRecommendedDetecting real MIME types of uploadsWeaker upload validation; type errors
intlRecommendedLocale-aware formatting, IDN domainsSome plugins degrade
zipRecommendedInstalling and updating plugins and themesSlower PclZip fallback; some update failures
xml, dom, simplexmlRecommendedFeeds, importers, SVG sanitising, sitemapsImport and feed errors
sodiumRecommendedModern cryptography (core includes a fallback)Slower fallback
opcacheStrongly recommendedCompiled code cacheMuch higher CPU per request
redis / memcachedOptionalPersistent object cacheObject cache plugin cannot connect

Site Health → Status warns about missing required and recommended modules.

PHP directives: what each setting does

DirectivePHP defaultTypical WordPress exampleWhat it does and how it affects WordPress
memory_limit128M256M (512M for heavy WooCommerce/builder sites)Maximum memory one request may use. WordPress raises its own limits up to WP_MEMORY_LIMIT (front end) and WP_MAX_MEMORY_LIMIT (admin, default 256M), but only if the host allows. A hard host cap wins.
max_execution_time30 (0 on CLI)60–120CPU-time limit for a script (on Linux, time spent waiting on the network or database does not count). Exceeding it gives "Maximum execution time of N seconds exceeded".
max_input_time-1 (unlimited; php.ini-production sets 60)60–300Time allowed to parse request input, including uploads. Slow upload connections hit this.
max_input_vars10003000–5000Maximum number of input variables. Large menus, page-builder layouts and settings pages exceed 1000, and extra fields are silently dropped, so menus "lose" items on save.
upload_max_filesize2M32M–128MMaximum size of each uploaded file.
post_max_size8MLarger than upload_max_filesizeMaximum size of the whole POST body. Exceeding it empties $_POST and $_FILES entirely.
max_file_uploads2020Files per request; extra files are dropped.
display_errorsVaries by buildOff in productionPrints errors into page output. On production it leaks paths and breaks JSON/REST responses (causing "Invalid JSON response" in the editor).
log_errors / error_logOn / server defaultOn / private pathWrites errors to a log file. Always on; make sure the log is outside the web root and rotated.
error_reportingE_ALLE_ALL (log everything; display nothing)Which error levels are reported. WordPress adjusts it when WP_DEBUG is set.
opcache.enable11Enables the opcode cache.
opcache.memory_consumption128 (MB)128–256Shared memory for compiled code. Too small causes constant recompilation (check the hit rate and "cache full" status).
opcache.max_accelerated_files1000010000–20000Number of script files cached. WordPress with many plugins can exceed 10,000 files.
opcache.validate_timestamps / revalidate_freq1 / 21 / 2–60Whether PHP checks for changed files. If timestamps are not validated, updated plugin files do not take effect until PHP-FPM reloads.

Where to set PHP values (when you do not have root)

MethodWorks withNotes
Hosting panel "PHP settings" / "MultiPHP INI Editor"Most shared and managed hostsThe safest method; writes the right file for you
.user.ini in the site rootPHP-FPM / CGI / LSAPIPer-directory INI file; re-read every user_ini.cache_ttl seconds (300 by default)
php.ini in the site rootSome suPHP/CGI hostsHost-specific; ignored on many platforms
php_value in .htaccessOnly Apache mod_php (and LiteSpeed, which emulates it)On PHP-FPM it causes a 500 Internal Server Error
Pool config (php_admin_value in the FPM pool)Root/VPSValues set with php_admin_value cannot be overridden by the site
define( 'WP_MEMORY_LIMIT', '256M' );WordPressRaises memory only up to what PHP permits
; Example for a mid-sized content site on PHP-FPM. Confirm limits with your host first.
memory_limit = 256M
max_execution_time = 120
max_input_time = 120
max_input_vars = 5000
upload_max_filesize = 64M
post_max_size = 72M
display_errors = Off
log_errors = On
; error_log must point to a path outside the web root that the PHP user can write:
; error_log = /home/example/logs/php-error.log
Verify

Site Health → Info → Server (and the Constants section) shows effective values. Allow up to 5 minutes for .user.ini changes.

What could go wrong

Syntax errors are usually ignored silently; php_value in .htaccess on FPM gives a 500 error; values above host caps are silently clamped.

Rollback

Restore or delete the file; values return to server defaults after the cache TTL or a PHP-FPM reload.

Escalate when

Values do not change despite correct configuration. The host enforces them with php_admin_value or plan limits.

Memory exhaustion and why "just add more memory" fails

When a request needs more memory than memory_limit allows, PHP stops immediately with a fatal error:

PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 20480 bytes)
in /var/www/example.com/public/wp-content/plugins/example-plugin/includes/report.php on line 812

Visitors see a critical-error message or a blank page. The file named is where memory ran out, which is not always where it was consumed. The tiny "tried to allocate" amount shows the limit was simply reached, often after a loop loaded thousands of posts or a large dataset into memory.

Raising the limit is right when the work is legitimately large (big image processing, a large import, a reasonable admin report) and the server has memory to spare. It is wrong as a reflex, for these reasons:

  • Memory is multiplied by concurrency. 30 workers × 1 GB limit = 30 GB that the server does not have. Under load, the operating system starts killing processes and the whole server becomes unstable.
  • It hides bugs. A plugin loading every order into memory on every page load will exhaust 512 MB next month as the data grows. The real fix is pagination, batching or a better query.
  • Host caps make it pointless. On shared hosting the effective limit is fixed; raising the WordPress constant does nothing.

Investigate with Query Monitor (peak memory per page), the slow log, and by isolating which plugin's code appears in the error path. Escalate to the plugin developer with the full error, or to your host if the limit is below the WordPress baseline (128–256 MB).

Timeouts: why they occur and which layer timed out

A request passes through several layers, each with its own timer. The shortest one ends the request, and the error you see depends on which layer gave up:

LayerSetting (examples)Typical defaultWhat the user sees
Browser—MinutesSpinner, then a browser error
CDN / proxyOrigin response timeoutOften 100 seconds504, or a CDN-specific timeout code (for example Cloudflare 524)
Nginx → PHP-FPMfastcgi_read_timeout60 s504 Gateway Timeout
Apache → PHP-FPMProxyTimeout / Timeout60 s504 or 503
PHP-FPMrequest_terminate_timeout0 (off) unless the host sets it502 (worker killed)
PHPmax_execution_time30 sFatal error: maximum execution time exceeded
Databasewait_timeout, lock waitsVaries"MySQL server has gone away", lock wait timeout errors
Outbound HTTPPer-call timeout in wp_remote_get()5 s in coreFeature fails; or the page waits if the plugin set a long timeout

Long-running work (imports, exports, bulk emails, report generation, large backups) should not run inside a web request. Move it to background processing (Action Scheduler, WP-CLI, a system cron job) and process it in small batches. Raising every timeout to 600 seconds just lets slow requests hold workers longer, which turns one slow page into a site-wide outage.

How inefficient plugins consume server resources

  • Work on every request: loading large settings, running queries or calling APIs on init even on pages that do not use the feature.
  • Bloated autoloaded options: storing megabytes in options with autoload enabled, read on every request including cached-miss and AJAX requests.
  • Unbounded queries: posts_per_page => -1, meta queries on unindexed values, LIKE '%term%' searches across large tables.
  • Remote calls without caching: fetching exchange rates, licence status or social counts on every page instead of storing them in a transient.
  • Excessive admin-ajax/Heartbeat: polling every few seconds from the admin or front end.
  • Cron storms: scheduling events every minute, or failing to clear old events, so wp_options.cron grows and every request checks a huge schedule.
  • Logging to the database: tables that grow by millions of rows without pruning.

Query Monitor (per-request queries, HTTP calls, hooks and memory) and an APM tool if your host offers one (New Relic and similar) show which plugin is responsible. Measure before and after deactivating a suspect on staging.

Hosting models: shared, VPS, managed and dedicated

Shared hostingVPS / cloud serverManaged WordPress hostingDedicated / cluster
ResourcesShared with many accounts; enforced per-account caps (CPU, RAM, processes, I/O, inodes)Guaranteed virtual CPU/RAM; you decide allocationPlan-defined PHP workers, storage and visits; platform-tunedWhole machines
Root accessNoYes (unless a managed VPS)No; some SSH/WP-CLIYes
Who maintains the OS, web server and PHPHostYou (or a control panel)HostYou or a provider
CachingPlugin-based; sometimes LiteSpeed or host cacheWhatever you installBuilt-in server/edge cache; often bans caching pluginsCustom
SecurityHost firewall and scanning; risk from neighbours depends on isolationYour responsibilityPlatform WAF, malware scanning, automatic core updates, sometimes plugin bansYour responsibility
Typical failure modesHitting entry-process or CPU limits (508/503), "resource limit reached", noisy neighboursMisconfiguration, unpatched OS, running out of RAMPHP worker limits, platform restrictions, cache behaviour you cannot seeComplexity
Best forSmall, mostly static sitesTeams with sysadmin skillsBusiness sites wanting expertise and supportHigh-traffic platforms

Shared hosting behaves differently from a VPS because limits are enforced per account, often by kernel-level tools such as CloudLinux LVE. Exceeding "entry processes" (concurrent requests) returns a 508 or 503 even when the server itself is idle. Managed WordPress hosting differs from traditional hosting in that the platform makes decisions for you: object and page caching, PHP worker counts, which plugins are allowed, and where configuration lives (often not in .htaccess at all). In exchange, you get platform-level updates, backups and support that understands WordPress. When a guide says "edit your php.ini" or "add this to .htaccess", check your host's documentation first. There is often a dashboard setting instead.

Apache, Nginx and LiteSpeed compared

Apache HTTP ServerNginxLiteSpeed (LSWS / OpenLiteSpeed)
How requests are handledMulti-Processing Modules: prefork (process per connection; required for mod_php), worker/event (threads; used with PHP-FPM). Can read per-directory .htaccess on every request.Event-driven, a few worker processes handle thousands of connections asynchronously. Very efficient for static files and proxying.Event-driven like Nginx, with Apache-compatible configuration handling. Commercial LSWS is a drop-in Apache replacement on cPanel/DirectAdmin; OpenLiteSpeed is the open-source edition.
How PHP is executedmod_php (legacy, in-process) or PHP-FPM via mod_proxy_fcgiAlways external: PHP-FPM via fastcgi_passLSAPI (lsphp) process manager, optimised for LiteSpeed
How rewrite rules workmod_rewrite in .htaccess or virtual host config; WordPress writes its own rules automaticallytry_files and rewrite in server config only; WordPress cannot write themReads Apache mod_rewrite syntax in .htaccess (LSWS reads it like Apache; OpenLiteSpeed supports rewrites but may need a restart to apply .htaccess changes)
Where configuration usually lives/etc/apache2/ (Debian/Ubuntu) or /etc/httpd/ (RHEL), virtual hosts in sites-available/conf.d; per-directory .htaccess/etc/nginx/nginx.conf, /etc/nginx/sites-available/ or conf.d/; no per-directory filesLSWS: Apache configs plus WebAdmin console; OpenLiteSpeed: WebAdmin console and /usr/local/lsws/conf/
Common WordPress configuration issuesAllowOverride None (permalinks 404, .htaccess ignored); unsupported directives causing 500s; php_value under FPM; slow .htaccess lookupsMissing try_files (permalinks 404); PHP block order (uploads PHP executing); add_header inheritance; client_max_body_size 413s; plugins' .htaccess rules silently doing nothingMultiple page caches when another caching plugin runs alongside LSCache; .htaccess changes not applied until restart (OpenLiteSpeed); LSAPI process limits on shared hosts
What the hosting provider may controlModules, AllowOverride, ModSecurity rules, MPM, PHP handlerEverything in server blocks; you often get only a panel or "custom Nginx includes"Cache module, LSAPI limits, ModSecurity, which .htaccess features are honoured
Built-in page cachingmod_cache (rarely used for WordPress)FastCGI cache (needs a purge mechanism)LSCache, integrated with the LiteSpeed Cache plugin, with tag-based purging

Many hosts combine them: Nginx in front serving static files and proxying to Apache behind it (so .htaccess still works for dynamic requests but not for static files Nginx serves directly). In that hybrid, an .htaccess rule protecting a static file may have no effect. Always check which server answers by inspecting the Server response header, and confirm the full stack with your host.

Error reporting and PHP logs

Production should log everything and display nothing. Displayed errors leak file paths and data, and break JSON responses. Logged errors are your primary diagnostic tool.

  • Find the PHP log: hosting panels usually show it ("Errors", "Logs", or ~/logs/). Self-managed servers often use /var/log/php*-fpm.log for FPM process messages, while script errors go to the path in the error_log directive or to the web server's error log.
  • WordPress debug log: WP_DEBUG_LOG captures notices and warnings that WordPress-level code generates. Set it to a path string outside the web root rather than true.
  • Rotate logs: a never-rotated debug log can reach gigabytes and fill the disk.
  • Check the timestamp time zone: PHP logs often use UTC while WordPress shows local time. Align them when correlating events.

Chapter 10 explains how to read the errors you find.

Rather have someone else keep WordPress healthy?

Our managed hosting and care plans cover updates, backups, security monitoring and fixes like the ones in this handbook, so you can get on with running the business.

See Hosting & Care