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.
On this page
- PHP versions and compatibility
- PHP-FPM, workers and process limits
- PHP extensions WordPress uses
- PHP directives: what each setting does
- Memory exhaustion and why "just add more memory" fails
- Timeouts: why they occur and which layer timed out
- How inefficient plugins consume server resources
- Hosting models: shared, VPS, managed and dedicated
- Apache, Nginx and LiteSpeed compared
- 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
- Check the current version in Tools → Site Health → Info → Server.
- Update all plugins and themes first; developers fix compatibility in new releases.
- Clone to staging and switch staging to the target version (most hosting panels offer a per-site PHP selector).
- Enable logging (
WP_DEBUG_LOGto a private path) and exercise the site: front end, admin, forms, checkout, cron tasks, imports. - Fix or replace anything that produces fatal errors or warnings. Deprecation notices are a to-do list for the next upgrade.
- 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:
| Directive | What it controls | Effect on WordPress |
|---|---|---|
pm | Process 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_children | Maximum simultaneous workers | The 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_servers | Worker counts for dynamic mode | Too few spares cause spawn delays during bursts |
pm.max_requests | Requests a worker serves before being recycled | Contains slow memory leaks in plugins; 500–1000 is common |
request_terminate_timeout | Hard kill for a single request | Overrides max_execution_time in some situations; too low kills imports and backups |
request_slowlog_timeout + slowlog | Logs a stack trace for requests slower than N seconds | Very 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.phpcalls (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
| Extension | Status | Used for | If missing |
|---|---|---|---|
mysqli | Required | Database connection | "Your PHP installation appears to be missing the MySQL extension" |
json | Required (built-in in PHP 8) | REST API, block editor, settings | Fatal errors |
curl | Highly recommended | HTTP requests: updates, APIs, payment gateways | Slower fallback transports; some gateways fail |
openssl | Highly recommended | HTTPS requests, signature checks for updates | Update and API failures |
mbstring | Recommended | Multibyte text handling | Broken non-ASCII text in some plugins |
imagick or gd | Recommended (one at least) | Image resizing, thumbnails, WebP/AVIF | No thumbnails; image processing errors |
exif | Recommended | Reading image orientation and metadata | Rotated photos |
fileinfo | Recommended | Detecting real MIME types of uploads | Weaker upload validation; type errors |
intl | Recommended | Locale-aware formatting, IDN domains | Some plugins degrade |
zip | Recommended | Installing and updating plugins and themes | Slower PclZip fallback; some update failures |
xml, dom, simplexml | Recommended | Feeds, importers, SVG sanitising, sitemaps | Import and feed errors |
sodium | Recommended | Modern cryptography (core includes a fallback) | Slower fallback |
opcache | Strongly recommended | Compiled code cache | Much higher CPU per request |
redis / memcached | Optional | Persistent object cache | Object cache plugin cannot connect |
Site Health → Status warns about missing required and recommended modules.
PHP directives: what each setting does
| Directive | PHP default | Typical WordPress example | What it does and how it affects WordPress |
|---|---|---|---|
memory_limit | 128M | 256M (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_time | 30 (0 on CLI) | 60–120 | CPU-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–300 | Time allowed to parse request input, including uploads. Slow upload connections hit this. |
max_input_vars | 1000 | 3000–5000 | Maximum 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_filesize | 2M | 32M–128M | Maximum size of each uploaded file. |
post_max_size | 8M | Larger than upload_max_filesize | Maximum size of the whole POST body. Exceeding it empties $_POST and $_FILES entirely. |
max_file_uploads | 20 | 20 | Files per request; extra files are dropped. |
display_errors | Varies by build | Off in production | Prints errors into page output. On production it leaks paths and breaks JSON/REST responses (causing "Invalid JSON response" in the editor). |
log_errors / error_log | On / server default | On / private path | Writes errors to a log file. Always on; make sure the log is outside the web root and rotated. |
error_reporting | E_ALL | E_ALL (log everything; display nothing) | Which error levels are reported. WordPress adjusts it when WP_DEBUG is set. |
opcache.enable | 1 | 1 | Enables the opcode cache. |
opcache.memory_consumption | 128 (MB) | 128–256 | Shared memory for compiled code. Too small causes constant recompilation (check the hit rate and "cache full" status). |
opcache.max_accelerated_files | 10000 | 10000–20000 | Number of script files cached. WordPress with many plugins can exceed 10,000 files. |
opcache.validate_timestamps / revalidate_freq | 1 / 2 | 1 / 2–60 | Whether 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)
| Method | Works with | Notes |
|---|---|---|
| Hosting panel "PHP settings" / "MultiPHP INI Editor" | Most shared and managed hosts | The safest method; writes the right file for you |
.user.ini in the site root | PHP-FPM / CGI / LSAPI | Per-directory INI file; re-read every user_ini.cache_ttl seconds (300 by default) |
php.ini in the site root | Some suPHP/CGI hosts | Host-specific; ignored on many platforms |
php_value in .htaccess | Only 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/VPS | Values set with php_admin_value cannot be overridden by the site |
define( 'WP_MEMORY_LIMIT', '256M' ); | WordPress | Raises 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:
| Layer | Setting (examples) | Typical default | What the user sees |
|---|---|---|---|
| Browser | — | Minutes | Spinner, then a browser error |
| CDN / proxy | Origin response timeout | Often 100 seconds | 504, or a CDN-specific timeout code (for example Cloudflare 524) |
| Nginx → PHP-FPM | fastcgi_read_timeout | 60 s | 504 Gateway Timeout |
| Apache → PHP-FPM | ProxyTimeout / Timeout | 60 s | 504 or 503 |
| PHP-FPM | request_terminate_timeout | 0 (off) unless the host sets it | 502 (worker killed) |
| PHP | max_execution_time | 30 s | Fatal error: maximum execution time exceeded |
| Database | wait_timeout, lock waits | Varies | "MySQL server has gone away", lock wait timeout errors |
| Outbound HTTP | Per-call timeout in wp_remote_get() | 5 s in core | Feature 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
initeven 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.crongrows 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.
Apache, Nginx and LiteSpeed compared
| Apache HTTP Server | Nginx | LiteSpeed (LSWS / OpenLiteSpeed) | |
|---|---|---|---|
| How requests are handled | Multi-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 executed | mod_php (legacy, in-process) or PHP-FPM via mod_proxy_fcgi | Always external: PHP-FPM via fastcgi_pass | LSAPI (lsphp) process manager, optimised for LiteSpeed |
| How rewrite rules work | mod_rewrite in .htaccess or virtual host config; WordPress writes its own rules automatically | try_files and rewrite in server config only; WordPress cannot write them | Reads 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 files | LSWS: Apache configs plus WebAdmin console; OpenLiteSpeed: WebAdmin console and /usr/local/lsws/conf/ |
| Common WordPress configuration issues | AllowOverride None (permalinks 404, .htaccess ignored); unsupported directives causing 500s; php_value under FPM; slow .htaccess lookups | Missing try_files (permalinks 404); PHP block order (uploads PHP executing); add_header inheritance; client_max_body_size 413s; plugins' .htaccess rules silently doing nothing | Multiple 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 control | Modules, AllowOverride, ModSecurity rules, MPM, PHP handler | Everything 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 caching | mod_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.logfor FPM process messages, while script errors go to the path in theerror_logdirective or to the web server's error log. - WordPress debug log:
WP_DEBUG_LOGcaptures notices and warnings that WordPress-level code generates. Set it to a path string outside the web root rather thantrue. - 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