Skip to content
Tutorials Center
My learning

Topics

Lesson 124 of 147 ยท Modern PHP and Ecosystem

Deploying PHP Applications

Take PHP to production - safe php.ini settings, PHP-FPM and nginx, environment variables, Composer --no-dev, OPcache, logs, health checks and zero-downtime deploys.

Code that works on your laptop is only half done. Deployment is everything between "it works for me" and "it works for every visitor, every day": a server configured for safety and speed, secrets kept out of the code, dependencies installed the right way, errors logged instead of shown, and a release process that doesn't take the site down or leave it half updated.

This lesson walks through a production setup step by step: the php.ini settings that matter, how PHP-FPM and nginx work together, configuration through environment variables, Composer in production, OPcache, logging, health checks, and zero-downtime deploys with release folders. The server configuration is shown as read-only files, while the runnable examples let you practice the PHP side: checking settings, loading configuration, writing structured logs and switching releases atomically. For background, How PHP Works explains the request cycle and Performance and OPcache the caching layer.

Production php.ini settings

PHP ships with two sample configuration files, php.ini-development and php.ini-production. Start from the production one. These are the settings that matter most:

INI
; Errors: log them, never show them to visitors
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/log/php/app-error.log
error_reporting = E_ALL

; Don't advertise the PHP version in the X-Powered-By header
expose_php = Off

; Limits
memory_limit = 256M
max_execution_time = 30
post_max_size = 20M
upload_max_filesize = 16M

; Sessions over HTTPS only, not readable by JavaScript
session.cookie_secure = On
session.cookie_httponly = On
session.cookie_samesite = Lax
session.use_strict_mode = 1

; Assertions compiled out entirely
zend.assertions = -1

; Time zone
date.timezone = UTC

; OPcache (see below)
opcache.enable = 1
opcache.validate_timestamps = 0

Two more directives are handy for cross-cutting code. auto_prepend_file names a PHP file that runs before every main script, and auto_append_file one that runs after it:

INI
auto_prepend_file = /var/www/app/bootstrap.php
auto_append_file  = /var/www/app/shutdown-metrics.php

That is how some applications load an autoloader or a security filter for every request without editing each page. Use them sparingly: the effect is invisible when you read a script, so document it. A script that calls exit skips the appended file. Under PHP-FPM you can also set them per directory in a .user.ini file, and under Apache with php_value in .htaccess.

The most important line is display_errors = Off. An error message shown to a visitor can reveal file paths, SQL queries and even credentials (Errors, Warnings and Notices). Errors still get logged, with error_reporting = E_ALL, so you see everything while visitors see a generic error page. Secure Coding Checklist lists further hardening settings.

A good habit is a small script that checks these settings, run once after setting up a server or as part of a deploy. Our editor uses development-style settings, so this check finds problems on purpose:

PHP A production settings check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The check reports that display_errors is on, log_errors and expose_php don't match, and assertions are enabled, which is exactly right for a learning environment and exactly wrong for a public server. In a deploy pipeline you'd make the script exit with code 1 when it finds problems, so the deploy stops (Command-Line PHP). Remember that the CLI and PHP-FPM can load different php.ini files; run the check through the web server too (from a protected URL) or compare php --ini with what phpinfo() reports.

PHP-FPM and nginx

On a typical Linux server, nginx accepts HTTP connections, serves static files (CSS, images, JavaScript) itself, and forwards requests for PHP to PHP-FPM (FastCGI Process Manager), a pool of PHP worker processes. Each worker handles one request at a time, then takes the next.

NGINX
server {
    listen 443 ssl;
    http2 on;
    server_name shop.example.com;

    root /var/www/shop/current/public;      # only public/ is reachable from the web
    index index.php;

    ssl_certificate     /etc/letsencrypt/live/shop.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/shop.example.com/privkey.pem;

    location / {
        try_files $uri $uri/ /index.php?$query_string;   # front controller
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        fastcgi_pass unix:/run/php/php8.5-fpm.sock;
    }

    location ~ /\.(?!well-known) {
        deny all;                                # hide .env, .git and other dot files
    }
}

Three details deserve attention. The document root points to the public/ folder, so vendor/, .env, templates and logs can never be downloaded. try_files sends every URL that isn't a real file to index.php, the front controller from Front Controllers and Routing. And $realpath_root resolves symlinks, which matters for the release-folder deploys later in this lesson.

The PHP-FPM pool configuration decides how many workers run:

INI
; /etc/php/8.5/fpm/pool.d/shop.conf
[shop]
user = www-data
group = www-data
listen = /run/php/php8.5-fpm.sock

pm = dynamic
pm.max_children = 20        ; hard limit of simultaneous requests
pm.start_servers = 5
pm.min_spare_servers = 3
pm.max_spare_servers = 8
pm.max_requests = 500       ; recycle workers to contain memory leaks

request_terminate_timeout = 60s

pm.max_children is the key number. If each worker uses up to 60 MB and the server has 2 GB to spare for PHP, about 30 workers fit. Too few and requests queue up; too many and the server runs out of memory and starts swapping, which is much worse. Measure your real per-request memory before you tune it.

Configuration with environment variables

Code is the same on every server; configuration is what differs: database passwords, API keys, the app URL, the debug flag. Keep configuration out of the code and out of Git, and pass it in through environment variables. PHP reads them with getenv() or $_ENV (the latter only when variables_order includes E). Locally, many projects keep them in a .env file that a library loads, and commit only a .env.example with placeholders.

Read environment variables in one place, validate them at startup, and fail loudly when a required one is missing. A typo in a variable name should stop the app at boot, not cause a strange error hours later:

PHP Loading configuration from the environment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first attempt fails with Missing required environment variable DB_PASSWORD, then the second succeeds. Notice the safe defaults: if APP_ENV or APP_DEBUG is forgotten, the app assumes production with debugging off, never the other way around. Frameworks cache their configuration in production (Laravel's config:cache), so the environment is read once per deploy rather than on every request.

Never commit real secrets to Git, even in a private repository. Anyone with access to the history (former employees, a leaked laptop, a CI service) can read them forever. If a secret was ever committed, rotate it: change the password or key, don't just delete the line.

Composer in production

On the server, install dependencies from the lock file so production runs exactly the versions you tested, and leave out development tools:

Terminal
composer install --no-dev --optimize-autoloader --no-interaction --prefer-dist
  • install (never update) reads composer.lock, so no surprise upgrades happen during a deploy (Autoloading and Composer).
  • --no-dev skips PHPUnit, debug toolbars and other require-dev packages: less code to load and less attack surface.
  • --optimize-autoloader (-o) builds a class map so the autoloader doesn't search folders. --classmap-authoritative (-a) goes further and never touches the file system for unknown classes.

Front-end assets (npm ci && npm run build) are built during the deploy or in CI too, so the server never needs to compile anything at request time.

OPcache and restarting PHP

As covered in Performance and OPcache, production runs with opcache.validate_timestamps=0: PHP never checks whether files changed. That's fast, and it means every deploy must reset OPcache, or the old code keeps running. The usual way is a graceful reload of PHP-FPM, which lets busy workers finish their current request first:

Terminal
sudo systemctl reload php8.5-fpm

Logs and monitoring

Once errors are hidden from visitors, logs are how you find out about them. Write logs somewhere that survives deploys (not inside the release folder), rotate them so the disk doesn't fill up (logrotate), and send serious errors to a service that alerts you (Sentry, Bugsnag, Flare or a log platform).

In containers and many cloud platforms, the convention is different: write logs to STDERR as one JSON object per line, and let the platform collect them. Structured fields make logs searchable ("all errors for order 1234"):

PHP Structured JSON logs on STDERR

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The time is fixed so the output is predictable; a real logger uses the current time. The uncaught exception is logged as a critical JSON line on STDERR, while STDOUT, which a visitor would see, gets only a polite message. The script then exits with code 1 on purpose, which the editor reports. Custom Exceptions and Error Handling Strategy goes deeper into handlers, and libraries like Monolog implement PSR-3 logging with dozens of destinations.

Add a health check too: a URL like /health that a load balancer or uptime monitor requests every few seconds. It should check what the app needs (the database, the cache, disk space), answer quickly, and return 200 when healthy and 503 when not, so traffic can be routed away from a broken server.

Zero-downtime deploys with release folders

The naive deploy is "copy the new files over the old ones". During the copy, some files are new and some are old, and a request arriving in the middle can load a mix and crash. A failed copy leaves the site broken with no easy way back.

The standard solution is release folders plus a symlink:

TEXT
/var/www/shop/
โ”œโ”€โ”€ releases/
โ”‚   โ”œโ”€โ”€ 20261017-142233/
โ”‚   โ””โ”€โ”€ 20261018-093000/     <- the new release, fully prepared
โ”œโ”€โ”€ shared/
โ”‚   โ”œโ”€โ”€ .env                 <- linked into every release
โ”‚   โ””โ”€โ”€ storage/             <- uploads, logs: survive deploys
โ””โ”€โ”€ current -> releases/20261018-093000

Each deploy creates a new folder, installs everything inside it (code, composer install, built assets, cached config), links the shared files in, and runs database migrations. Only when the new release is completely ready does the current symlink switch to it, and nginx serves current/public. If something goes wrong, rolling back is switching the symlink to the previous folder.

The switch itself must be atomic: at no moment can current be missing. Replacing a symlink in place isn't atomic, but rename() is: create the new link under a temporary name, then rename it over the old one. Here's that technique in PHP, run in a temporary folder:

PHP Switching releases atomically

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each activate() swaps the live version instantly, and the rollback is just another switch. The release folders stay on disk, so deploy tools keep the last few and delete older ones. Tools like Deployer, Envoyer, Laravel Forge and Ploi automate this whole flow, including running migrations and reloading PHP-FPM.

Make database migrations backward compatible: during the switch, old code may still be running against the new schema. Add a column in one deploy and start using it in the next; remove an old column only after no running code reads it.

A typical deploy script, whatever tool runs it, looks like this:

Terminal
#!/usr/bin/env bash
set -euo pipefail

RELEASE=/var/www/shop/releases/$(date +%Y%m%d-%H%M%S)
git clone --depth 1 --branch main [email protected]:acme/shop.git "$RELEASE"
cd "$RELEASE"

composer install --no-dev --optimize-autoloader --no-interaction
npm ci && npm run build
ln -s /var/www/shop/shared/.env .env
ln -s /var/www/shop/shared/storage storage

php bin/migrate.php                     # backward-compatible migrations
php bin/check-production.php            # the settings check from earlier

ln -sfn "$RELEASE" /var/www/shop/current.tmp
mv -T /var/www/shop/current.tmp /var/www/shop/current   # atomic switch
sudo systemctl reload php8.5-fpm                         # reset OPcache gracefully

set -euo pipefail makes the script stop at the first failing command, so a broken composer install never reaches the switch. Better still, run the tests in CI first and deploy only builds that passed (Testing PHP Code).

Containers

Many teams package the application as a Docker image instead: PHP, extensions, configuration and code in one immutable artifact that runs the same on a laptop, in CI and in production. A new release is a new image; the orchestrator (Docker Compose, Kubernetes, or a managed platform) starts new containers, waits for their health checks, then stops the old ones, which gives you zero-downtime deploys for free.

DOCKERFILE
FROM php:8.5-fpm-alpine

RUN docker-php-ext-install pdo_mysql opcache
COPY docker/php-production.ini /usr/local/etc/php/conf.d/zz-production.ini

COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
WORKDIR /var/www/app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --no-autoloader --prefer-dist
COPY . .
RUN composer dump-autoload --optimize --classmap-authoritative

USER www-data

Copying composer.json and composer.lock before the rest of the code lets Docker reuse the cached dependency layer when only your code changes, which makes builds much faster. Configuration still comes from environment variables, and logs go to STDERR, which is why those two habits from earlier in this lesson matter so much.

Where to host

  • Shared hosting: cheap and simple, but limited control (old PHP versions, no SSH or Composer on some plans). Fine for a small WordPress site.
  • A virtual server (VPS) from providers like Hetzner, DigitalOcean or AWS Lightsail, managed by you or by a provisioning tool such as Laravel Forge or Ploi: full control at low cost.
  • Platform as a service: you push code and the platform runs it, scaling for you (Laravel Cloud, Platform.sh / Upsun, Heroku-style platforms).
  • Containers on Kubernetes or a managed container service, for teams that already operate them.

Whichever you choose, put a CDN or reverse proxy in front for static files and caching, use HTTPS everywhere (Let's Encrypt certificates are free), back up the database and uploaded files automatically, and test that the backups actually restore.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must display_errors be Off on a production server?

    Visitors should see a generic error page. With log_errors On and error_reporting E_ALL, you still see every error in the log.
  2. 2. Why does the nginx config set root to the project's public/ folder?

    Only public/ (index.php and assets) should be reachable. Everything else, including configuration and dependencies, stays outside the web root.
  3. 3. What does composer install --no-dev do on the server?

    install reads the lock file, so production runs the tested versions. --no-dev leaves out development tools, reducing code and attack surface.
  4. 4. In a release-folder deploy, why create the new symlink under a temporary name and then rename() it over current?

    Deleting and recreating the link leaves a short gap where requests fail. Renaming over an existing path is atomic on Linux file systems.
  5. 5. An app reads APP_DEBUG from the environment. What should happen if the variable is missing on a server?

    Defaults must be the safe choice (production, debug off). Values the app can't work without should fail loudly at startup with a clear message.

Summary

  • Start from php.ini-production: display_errors=Off, log_errors=On, error_reporting=E_ALL, expose_php=Off, secure session cookies, zend.assertions=-1, OPcache on with validate_timestamps=0. Check the settings with a script.
  • nginx serves static files and passes PHP requests to a PHP-FPM pool; point root at public/, route everything else to index.php, and size pm.max_children by memory.
  • Keep configuration in environment variables, validate them at startup, default to safe values and never commit secrets.
  • Install dependencies with composer install --no-dev --optimize-autoloader, and reload PHP-FPM after each deploy to reset OPcache.
  • Log errors where they survive deploys (or as JSON on STDERR in containers), alert on serious ones, and expose a fast /health check.
  • Zero-downtime deploys build each release in its own folder, share .env and storage, run backward-compatible migrations, then switch a current symlink atomically; rollback is switching back.
  • Containers package PHP, extensions and code into one image; hosting ranges from shared hosting to VPSs, PaaS and Kubernetes.

Next: Project: To-Do List