The language that grew up with the web
When you open a web page, your browser sends a short text message, an HTTP request, to a server: "please give me /products?category=tea". Something on that server has to decide what to send back. For a static file it is easy: read the file, send it. But a shop's product list changes every minute, a news site's front page depends on who is logged in, and a form has to be checked and saved somewhere. Somebody has to write a program that runs for each request and builds the answer.
PHP was made for exactly that job, and it is still one of the most common ways to do it. A large share of the world's websites run on PHP, many of them through WordPress, which powers blogs, news sites and shops on every continent. MediaWiki, the software behind Wikipedia, is written in PHP. So are the popular frameworks Laravel and Symfony, which teams use to build everything from small business sites to large online services. Facebook was written in PHP in its early years before the company built its own dialect, Hack.
PHP is also an ordinary general-purpose scripting language. You can run it from a terminal to rename files, process a spreadsheet, or run a scheduled job, and that is how we will run it in this course, because it lets us see exactly what a program prints.
If you have heard that PHP is messy, it is worth knowing what changed. The PHP of the early 2000s let you mix database queries into HTML, compared "abc" and 0 as equal, and had few ways to catch mistakes early. Modern PHP, from version 7 (2015) and especially version 8 (2020) on, has optional strict type checking, classes with typed and readonly properties, enums, pattern-like match expressions, a fast engine with a just-in-time compiler, a standard package manager (Composer) and shared community standards. Old code still runs, which is part of PHP's value and part of its reputation, but new code looks very different. This course teaches the new code, and points out the old traps when you will meet them in existing projects.
From Personal Home Page Tools to PHP 8.6
In 1994 Rasmus Lerdorf, a Danish-Canadian programmer, wrote a few small programs in C to track visits to his online résumé. He kept adding to them, released them publicly in June 1995 as Personal Home Page Tools, and soon added a way to process HTML forms. The name PHP comes from those first tools; later it was given the recursive meaning PHP: Hypertext Preprocessor.
The language's shape was set by others who joined. In 1997 two Israeli developers, Andi Gutmans and Zeev Suraski, rewrote the parser for PHP 3 (1998), which made PHP extensible and turned it from one person's toolkit into a community project. Their next rewrite, the Zend Engine, became the heart of PHP 4 (2000) and every version since. PHP 5 (2004) brought a real object model with classes, interfaces and exceptions, and PDO, the database layer you will use later in this course, arrived in PHP 5.1.
An ambitious PHP 6, meant to make every string Unicode, was abandoned. The next major version, PHP 7 (December 2015), rebuilt the engine's internal data structures, which made typical applications much faster and far less hungry for memory. It also introduced scalar type declarations, return types and the strict_types mode. PHP 8.0 (November 2020) added named arguments, union types, the match expression, the nullsafe operator ?->, attributes and a just-in-time (JIT) compiler. The 8.x releases since then, one a year near the end of the year, added enums and readonly properties (8.1), readonly classes (8.2), typed class constants (8.3), property hooks and asymmetric visibility (8.4), the pipe operator |> and clone with new property values (8.5), and partial function application and clamp() (8.6). This course was tested with PHP 8.6, and it marks features newer than 8.0 with the version that introduced them, because you will often work on servers that run an older release.
Since 2021 the PHP Foundation, a non-profit backed by companies that depend on PHP, has paid core developers to maintain the language. Changes are proposed as public RFCs (requests for comments) on wiki.php.net/rfc and decided by a vote of core contributors, so you can read exactly why each feature exists.
The pieces: engine, SAPIs, extensions and php.ini
A few words will come up again and again.
Definition— Zend Engine
The core of PHP: it parses your source file, compiles it to opcodes (instructions for a virtual machine), and runs them. The OPcache extension keeps compiled opcodes in memory so a busy server does not recompile the same file on every request; the optional JIT can go further and turn hot opcodes into machine code.
Definition— SAPI (Server API)
The layer that connects the engine to the outside world. The CLI SAPI is the php command you run in a terminal. PHP-FPM (FastCGI Process Manager) is the SAPI most production web servers use: a pool of PHP worker processes that a web server such as nginx or Apache hands requests to. The constant PHP_SAPI tells a script which one it is running under.
Definition— Extension
A module, usually written in C, that adds functions and classes: json, pdo_sqlite, mbstring (multibyte strings), intl, curl and many more. Which extensions exist depends on how your PHP was built or packaged; php -m lists them. When a function "does not exist", a missing extension is the usual reason.
Definition— php.ini
PHP's configuration file: memory limits, which errors are shown, upload sizes, which extensions load. php --ini shows which file your PHP reads. Development and production need different settings (most importantly, never display errors to visitors in production), and PHP ships a sample of each.
PHP releases a new minor version every year, usually in late November. Each one gets about two years of bug fixes and then two more of security fixes; the supported versions page shows the current dates. A professional habit is to know which version your production servers run and to plan upgrades before support ends.
Installing PHP and running a first script
Installing. On Linux, your distribution's package manager has PHP (for example sudo apt install php-cli on Debian and Ubuntu); distributions often lag behind the newest release, and community repositories exist for the latest. On macOS, brew install php with Homebrew is the common route. On Windows, download a build from windows.php.net, unzip it and add the folder to your PATH. With Docker, docker run --rm -it php:cli php -a gives you a PHP shell without installing anything. Check that it worked:
php --version
php -m # the extensions you have
php --ini # which php.ini file is usedA first script. PHP files end in .php. Everything outside a <?php tag is copied to the output unchanged, and everything inside is code. A file that contains only code starts with <?php and, by convention, has no closing tag. Save this as hello.php and run php hello.php:
<?php
// A first PHP program. Run it with: php hello.php
$name = "Amara";
$firstYear = 1995;
$age = 2026 - $firstYear;
echo "Hello, $name!\n";
echo "PHP first appeared in $firstYear, so in 2026 it is $age years old.\n";
echo 'Single quotes print $name literally.', "\n";
echo "Concatenation uses a dot: " . strtoupper($name) . "\n";
printf("%s has %d letters and %.1f%% of them are vowels.\n", $name, strlen($name), 3 / 5 * 100);It prints:
Hello, Amara!
PHP first appeared in 1995, so in 2026 it is 31 years old.
Single quotes print $name literally.
Concatenation uses a dot: AMARA
Amara has 5 letters and 60.0% of them are vowels.Read it line by line:
- Every variable starts with
$. You create one by assigning to it; there is no declaration keyword. - Statements end with a semicolon.
echowrites its arguments to the output. It is a language construct, not a function, so it needs no parentheses, and it accepts several arguments separated by commas.- In a double-quoted string,
$nameis replaced by the variable's value (this is called interpolation) and\nis a newline. A single-quoted string is taken literally, apart from\'and\\. - The dot
.joins strings. PHP keeps+for numbers, which avoids a whole class of confusion found in some other languages. printfformats like C's:%sa string,%dan integer,%.1fa number with one decimal,%%a literal percent sign.//starts a comment to the end of the line;#also works, and/* … */spans lines.
PHP as a template language
PHP began as a way to put small pieces of logic inside HTML, and it still works that way. The short tag <?= expr ?> means "echo this expression", and loops have an alternative syntax with a colon and endforeach that reads well between HTML lines:
<?php
$title = "Reading list";
$books = [
["title" => "Things Fall Apart", "author" => "Chinua Achebe"],
["title" => "The Tale of Genji", "author" => "Murasaki Shikibu"],
["title" => "Pedro Páramo", "author" => "Juan Rulfo"],
["title" => "Tom & Jerry's <Guide>", "author" => "Anonymous"],
];
?>
<h1><?= htmlspecialchars($title) ?></h1>
<ul>
<?php foreach ($books as $book): ?>
<li><?= htmlspecialchars($book["title"]) ?> by <?= htmlspecialchars($book["author"]) ?></li>
<?php endforeach; ?>
</ul>Run from the terminal, it prints the HTML a browser would receive:
<h1>Reading list</h1>
<ul>
<li>Things Fall Apart by Chinua Achebe</li>
<li>The Tale of Genji by Murasaki Shikibu</li>
<li>Pedro Páramo by Juan Rulfo</li>
<li>Tom & Jerry's <Guide> by Anonymous</li>
</ul>Two details matter. First, PHP swallows a single newline directly after a closing ?>, which is why the output has no blank lines where the PHP tags were. Second, look at the last book: htmlspecialchars turned &, ', < and > into HTML entities. Without it, a title containing <script> would become real code running in your visitors' browsers. Escaping every value you print into HTML is the single most important habit in web PHP, and a later lesson is devoted to it.
The $books array holds associative arrays, PHP's maps from keys to values, written with =>. Arrays are PHP's universal data structure, and they get their own lesson.
In real applications, templates usually live in separate files and are rendered by a template engine (Laravel's Blade or Symfony's Twig) that escapes output automatically. Knowing that underneath it is still "PHP printing text" makes those tools much less mysterious.
How a PHP program runs
A modern PHP command-line script looks like the next program: a strict-types declaration, a function with typed parameters, and the command-line arguments in $argv.
<?php
declare(strict_types=1);
function greet(string $name, string $greeting = "Hello"): string
{
return "$greeting, $name!";
}
$names = array_slice($argv, 1) ?: ["Wanjiru", "Tomás", "Mei"];
foreach ($names as $i => $name) {
echo $i + 1, ". ", greet($name), PHP_EOL;
}
echo greet("world", greeting: "Good morning"), PHP_EOL;
echo "SAPI: ", PHP_SAPI, ", arguments: ", count($argv), PHP_EOL;Run with no arguments, it prints:
1. Hello, Wanjiru!
2. Hello, Tomás!
3. Hello, Mei!
Good morning, world!
SAPI: cli, arguments: 1$argv always holds the script's own name first, so with no extra arguments its count is 1 and array_slice($argv, 1) is empty. The ?: operator ("short ternary") returns its left side if that is truthy and its right side otherwise, so the script falls back to three sample names. Run php greet.php Ana Kofi and it greets Ana and Kofi instead. PHP_EOL is the platform's line ending. The call greet("world", greeting: "Good morning") passes an argument by name, a PHP 8.0 feature you will use often. And declare(strict_types=1);, which must be the very first statement of a file, tells PHP to reject a call like greet(42) instead of quietly converting 42 to "42". The next lesson explains why professionals put it at the top of every file.
What happens when you run it. The engine reads the whole file, compiles it to opcodes, runs them from top to bottom, and exits. On a web server the same thing happens for every request: PHP-FPM hands the request to a worker, the worker runs your script with the request's data in variables such as $_GET and $_POST, the output becomes the response body, and then everything the script created is thrown away. This is called a shared-nothing architecture. It is one of PHP's great strengths: one request cannot leak memory or corrupt state into the next, and a crash affects one visitor, not all of them. It also means anything that must survive between requests (a logged-in user, a shopping basket) has to be stored somewhere outside the script: a session, a database, a cache.
Some newer servers for PHP (FrankenPHP, RoadRunner, Swoole) keep a worker and its loaded application in memory between requests for speed. They change that rule, and code written for them has to be careful about state; you will meet them in the last lesson.
Other ways to run PHP.
php -a # interactive shell: type statements, see results
php -r 'echo 2 ** 10, "\n";' # run one line of code
php -l hello.php # lint: check the syntax without running
php -S localhost:8000 # serve the current folder at http://localhost:8000The built-in web server is perfect for trying a page in your browser while you learn, and it is single-threaded and not hardened, so it is for development only. Production sites run behind nginx or Apache with PHP-FPM, or on a platform that sets that up for you.
Common misunderstandings
Misconception
"PHP files must end with ?>." In a file that contains only PHP code, leave the closing tag out. Anything after ?>, even an invisible space or newline at the end of the file, is sent to the output. In a web application that stray whitespace can arrive before your HTTP headers are sent and break redirects or file downloads. The community coding standard (PER Coding Style) says to omit it.
Misconception
"Single and double quotes are interchangeable." Only double-quoted strings interpolate $variables and understand escapes such as \n and \t. Use single quotes when you want the text exactly as written, and double quotes (or sprintf) when you want values inserted. Neither is faster in any way that matters.
Misconception
"A PHP variable keeps its value between page loads." In the classic setup, each request starts from nothing. A counter that you increment in a script will read 1 on every page load. To remember something, store it in a session, a database or a cache.
Misconception
"PHP is an old language, so tutorials from any year are fine." Code from before PHP 7 often shows patterns that are now removed (the mysql_* functions) or discouraged (building SQL by joining strings, comparing with == everywhere). Check the date and the PHP version of anything you learn from, and prefer the official manual.
Exercises
1. Getting started with PHP
Warm-upHumanYou run php report.php in a terminal, and the script prints PHP_SAPI. What does it print?
2. Getting started with PHP
Warm-upComputationalWhat does this program print?
<?php
$who = 'Ravi';
$items = 3;
echo "Hello, $who. ", 'You have $items items.', "\n";
3. Getting started with PHP
CoreComputationalWhat does this program print?
<?php
$items = 3;
printf("%d + %d = %d, %.2f\n", $items, 2, $items + 2, 10 / 4);
4. Getting started with PHP
CoreComputationalA script tool.php contains <?php echo count($argv), "\n";. You run php tool.php red green blue. What number does it print?
5. Getting started with PHP
CoreComputationalThis file mixes PHP and text. What does it print? (It prints one line.)
<?php $tag = "<b>Hi</b>"; ?>
[<?= htmlspecialchars($tag) ?>]
6. Getting started with PHP
CoreHumanWhy do PHP coding standards say to leave out the closing ?> in files that contain only PHP code?
7. Getting started with PHP
CoreHumanA page served by PHP-FPM runs $visits = ($visits ?? 0) + 1; echo $visits;. A visitor loads the page three times. What do they see the third time?
Further reading and resources
- DownloadsOfficial source releases and links to packaged builds for each operating system.
- PHP Manual: Installation and ConfigurationInstalling PHP on Linux, macOS and Windows, and configuring it with php.ini.
- PHP Manual: Using PHP from the command lineEvery option of the php command, the interactive shell and $argv.
- PHP Manual: Built-in web serverHow php -S works and why it is for development only.
- Supported versionsThe support timeline of each PHP release.
- The PHP FoundationThe non-profit, founded in 2021, that pays developers to work on the PHP language itself.