Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 147 ยท Getting Started

How PHP Works

Follow a web request from the browser through nginx and PHP-FPM and back, learn how PHP compiles code to opcodes, what OPcache and JIT do, and how to install PHP locally.

In Getting Started with PHP you ran a few scripts and saw their output. But what actually happens between typing a URL and seeing a page built by PHP? Who starts PHP, where does the output go, and why is PHP fast enough to serve millions of pages a day?

This lesson follows a request from the browser to PHP and back. You'll learn what a SAPI is, how PHP turns your source code into opcodes, what OPcache and the JIT do, and how to install PHP on your own computer. Knowing this model explains a lot of PHP's behavior later on, from why variables vanish between page loads to why "headers already sent" errors happen.

The request/response cycle

The web runs on HTTP, a simple conversation: a client (usually a browser) sends a request, and a server sends back a response. When you visit https://example.com/products?page=2, your browser sends something like this:

TEXT
GET /products?page=2 HTTP/1.1
Host: example.com
Accept: text/html
Cookie: theme=dark

On a PHP site, this is what happens next:

  1. The web server (nginx, Apache, Caddy and so on) receives the request. If it's for a static file such as logo.png or styles.css, the web server sends it directly. PHP is not involved.
  2. If the request needs PHP, the web server passes it to the PHP runtime, along with details such as the method, the path, the query string, headers and cookies.
  3. PHP runs your script. It fills special arrays like $_GET, $_POST, $_COOKIE and $_SERVER with the request data, then executes your code from top to bottom.
  4. Everything your script outputs (with echo, or HTML outside PHP tags) becomes the response body. Functions such as header() and http_response_code() set the status line and headers.
  5. The web server sends the response to the browser, and PHP throws away everything the script created: variables, objects, open files. The next request starts from scratch.

The response the browser receives might look like this:

TEXT
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8

<!DOCTYPE html>
<html lang="en">
<head><title>Products, page 2</title></head>
...

The browser never sees your PHP code. It only sees the output.

A simulated request

Our editor runs PHP on the command line, not behind a web server, so there's no real HTTP request. But you can simulate one: write the handler as a function that receives request data and returns a response. This mirrors what a framework does internally:

PHP Simulating a request and response

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.

This is only a simulation: a real server builds $query from the URL and sends the status line and headers over the network for you. You'll write real request handling in Superglobals and Handling Forms.

Shared-nothing: every request starts fresh

Step 5 above is one of PHP's defining traits. Each request runs in a clean environment and nothing survives to the next one unless you store it somewhere outside PHP: a database, a file, a cache like Redis, a cookie or a session.

Run this example several times:

PHP Nothing survives between runs

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.

It always prints Visit number: 1. The same thing happens on a website: a variable can't count page views by itself. This design is called shared-nothing, and it has big advantages:

  • A bug or crash in one request can't corrupt the next.
  • Memory leaks don't accumulate, because everything is freed after each request.
  • Scaling is easy: add more servers, and any of them can handle any request.

To remember things between requests you'll use Sessions, Cookies and databases (PHP and Databases).

SAPIs: how PHP plugs into its surroundings

PHP's core engine (called the Zend Engine) doesn't know about web servers or terminals. A layer called the SAPI (Server API) connects it to the outside world: it feeds input in and carries output out. The most important SAPIs are:

SAPI PHP_SAPI value Used for
CLI cli Running scripts in a terminal: php script.php. Also used by this editor.
PHP-FPM fpm-fcgi Production websites with nginx, Apache or Caddy.
Apache module apache2handler Older Apache setups with mod_php.
Built-in server cli-server php -S for local development.

PHP-FPM (FastCGI Process Manager) is the standard for production. It keeps a pool of PHP worker processes running. The web server forwards each PHP request to a free worker over the FastCGI protocol; the worker runs the script, returns the output, resets itself, and waits for the next request. Starting processes ahead of time avoids the cost of launching PHP for every request.

You can ask PHP which SAPI it's running under. Here it's the CLI, so there are command-line arguments in $argv but no HTTP method:

PHP Which SAPI is running?

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 same script behind PHP-FPM would print fpm-fcgi and a method such as GET. Code that must work in both places checks PHP_SAPI === 'cli'. The CLI has its own lesson later: Command-Line PHP.

From source code to opcodes

PHP is often called "interpreted", but it doesn't run your text directly. Each time a script runs, the engine goes through these stages:

  1. Lexing: the source text is split into tokens, the smallest meaningful pieces: variable names, operators, numbers, keywords.
  2. Parsing: tokens are arranged into an abstract syntax tree (AST), a structure that captures what the code means. This is where syntax errors such as a missing semicolon are found, which is why a parse error stops the whole file before any of it runs.
  3. Compiling: the AST is turned into opcodes, simple instructions for the Zend virtual machine, like "multiply these two values" or "echo this".
  4. Executing: the Zend Engine runs the opcodes one by one.

You can watch stage 1 yourself. The PhpToken class (PHP 8.0) splits code into tokens:

PHP Tokenizing PHP code

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 output shows names like T_VARIABLE for $total and T_LNUMBER for the integer 2. When PHP reports syntax error, unexpected token ";", it's talking about these tokens. Tools such as code formatters and static analyzers are built on the same tokens and AST.

OPcache: compile once, run many times

Lexing, parsing and compiling take time, and on a website the same files run thousands of times a minute without changing. OPcache is a built-in extension that stores the compiled opcodes in shared memory. The first request compiles a file; every later request skips straight to execution. On real applications, enabling OPcache often makes pages several times faster.

OPcache is enabled by default for web SAPIs in most installations. For the CLI it's usually off (opcache.enable_cli=0), because a command-line script runs once and exits, so there's nothing to reuse:

PHP Checking OPcache

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.

Here the extension is loaded, opcache.enable_cli is 0, and the JIT is disable. On a production server you'd see OPcache enabled. A typical production configuration looks like this (read-only):

INI
; php.ini (production)
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000
; Don't check files for changes on every request; reset OPcache on deploy instead.
opcache.validate_timestamps=0

With validate_timestamps=0, PHP never notices edited files until OPcache is reset, which is why deployment scripts reload PHP-FPM. Performance and OPcache and Deploying PHP Applications go deeper.

The JIT

PHP 8.0 added a JIT (just-in-time compiler), part of OPcache. It goes one step further: it translates hot opcodes into native machine code for your CPU. The JIT helps most with CPU-heavy work such as math, image processing or parsing. Typical web applications spend most of their time waiting for databases and networks, so the JIT changes their speed only a little. It's off unless you configure it (for example opcache.jit=tracing with a opcache.jit_buffer_size).

Mental model: source code โ†’ tokens โ†’ AST โ†’ opcodes โ†’ executed by the Zend Engine. OPcache caches the opcodes; the JIT can turn hot opcodes into machine code.

Installing PHP on your computer

The editors in this course need no installation, but sooner or later you'll want PHP locally. Choose one of these approaches.

All-in-one local environments

The easiest start on Windows and macOS is a bundle that installs PHP, a web server and usually a database together:

  • Laravel Herd (Windows, macOS): installs PHP and nginx, serves folders as http://project-name.test, and switches PHP versions with one click. Despite the name, it works for any PHP project.
  • XAMPP, MAMP, Laragon and similar: Apache, PHP and MariaDB/MySQL in one installer. Check that the bundle ships a current PHP 8 version.

Package managers

Terminal
# macOS (Homebrew)
brew install php

# Ubuntu / Debian
sudo apt install php-cli php-fpm php-mbstring php-xml php-sqlite3

Distribution packages sometimes lag behind the newest release. On Ubuntu and Debian, many developers use a dedicated repository that tracks current versions. On Windows without a bundle, download the official zip build from windows.php.net, unzip it (for example to C:\php) and add that folder to your PATH.

Docker

Docker runs PHP in a container, so every project can pin its own version without touching your system:

Terminal
docker run --rm -v "$PWD":/app -w /app php:8.5-cli php script.php

Checking your installation

Open a terminal and run:

Terminal
php -v          # prints the version, e.g. PHP 8.5.x (cli)
php -m          # lists the loaded extensions
php --ini       # shows which php.ini files are loaded
php script.php  # runs a script

If php -v shows an unexpected old version, another PHP is earlier on your PATH (common when several bundles are installed). Run where php on Windows or which php on macOS/Linux to find it.

A LAMP stack and phpMyAdmin

On Linux the classic setup is LAMP: Linux, Apache, MySQL (or MariaDB) and PHP. On Ubuntu or Debian you can install the pieces with the package manager:

Terminal
sudo apt update
sudo apt install apache2 mariadb-server php libapache2-mod-php php-mysql php-mbstring php-xml
sudo systemctl status apache2     # the web server (httpd on Red Hat-style systems)

Apache serves files from its document root: usually /var/www/html on Debian/Ubuntu, C:\xampp\htdocs for XAMPP on Windows and /opt/lampp/htdocs for XAMPP on Linux. Put an index.php there and open http://localhost/index.php. Bundles such as XAMPP and WAMP start Apache and the database from a small control panel instead.

phpMyAdmin is a web interface, written in PHP, for managing MySQL and MariaDB. XAMPP installs it for you (open http://localhost/phpmyadmin); on Ubuntu add it with sudo apt install phpmyadmin. After you log in with a database account, you can:

  • create, browse and drop databases and tables, and edit rows in a grid;
  • run SQL in the SQL tab and see the results;
  • build a query visually with the Query (query-by-example) tab, where you add or remove criteria rows;
  • import and export data (Import / Export tabs, for example as .sql or CSV files);
  • manage users and privileges, and run table Operations such as rename, copy, repair or optimize.

It is a convenient tool for a development machine. On a production server, restrict it to your own IP address or leave it out: a database administration page open to the internet is a favorite target for attackers. Use a database account with only the privileges the task needs, never root on a shared server.

Where PHP looks for its configuration

php --ini lists the loaded php.ini and the extra .ini files PHP read. The web SAPI and the CLI usually have separate files (for example /etc/php/8.5/apache2/php.ini and /etc/php/8.5/cli/php.ini), so a change in one does not affect the other. Restart Apache or PHP-FPM after editing for the web SAPI; the CLI reads the file on every start.

The built-in development server

PHP includes a tiny web server for local testing. Run it from the folder that contains your index.php:

Terminal
php -S localhost:8000

Then open http://localhost:8000 in your browser. Each request is handled by PHP with the cli-server SAPI and logged in the terminal. You can also name a router script (php -S localhost:8000 router.php) that runs for every request. The built-in server handles one request at a time and has no security hardening, so never use it in production.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A visitor requests /logo.png on a typical nginx + PHP-FPM site. What runs PHP?

    Web servers send static files such as images, CSS and JavaScript themselves. Only requests that need PHP are forwarded to PHP-FPM.
  2. 2. A script does $count = 0; $count++; echo $count;. What does the 100th request print?

    PHP is shared-nothing. Every request starts fresh, so $count begins at 0 every time and the script prints 1.
  3. 3. What does OPcache store?

    OPcache keeps compiled opcodes in shared memory so PHP can skip lexing, parsing and compiling on later requests. It does not cache output.
  4. 4. What does PHP_SAPI contain when a script runs in a terminal with php script.php?

    The command-line SAPI is cli. The built-in development server reports cli-server, and PHP-FPM reports fpm-fcgi.
  5. 5. Why does a missing semicolon stop the whole file, even code before the mistake?

    Parsing happens before execution. If the file can't be parsed into an AST, nothing in it runs.

Summary

  • A web server receives HTTP requests, serves static files itself and hands PHP requests to the PHP runtime, usually PHP-FPM.
  • PHP fills $_GET, $_POST, $_SERVER and friends, runs your script, and its output becomes the response.
  • PHP is shared-nothing: every request starts fresh, so persistent data lives in databases, files, caches, cookies or sessions.
  • A SAPI connects PHP to its environment: cli, fpm-fcgi, cli-server, apache2handler.
  • Source code becomes tokens, an AST, then opcodes that the Zend Engine executes. OPcache caches opcodes; the JIT (PHP 8.0) can compile hot code to machine code.
  • Install PHP with Herd or another bundle, a package manager or Docker; check it with php -v. php -S localhost:8000 is for development only.

Next: PHP Syntax, where you'll learn the rules for PHP tags, statements and mixing PHP with HTML.