Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Programming Shortcut: PHP

Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about request and response.

A little code inside a web page

In 1994 a programmer named Rasmus Lerdorf wanted to keep track of visits to his online résumé. He wrote a few small tools for the job and called them Personal Home Page Tools. He shared them, they grew support for guestbooks and forms, and a few rewrites later the result was a language. It still carries the initials.

So PHP wasn’t designed as a general-purpose language that later learned about the web. It started as a way to put a little code inside a web page, and it still is. Most languages give you a program that produces output. PHP gives you a page, with a program tucked inside it.

That makes PHP the clearest place to see how every website works. Behind any page you have ever loaded, a program received a message from your browser and sent one back. Big frameworks in big languages wrap that exchange in layers. PHP doesn’t bother. The exchange is right there in front of you, and you can watch it happen in your own terminal.

What you already have

You already know variables, decisions, loops, functions, arrays and records, so here they are in PHP’s spelling, and then we can leave them alone:

What you knowluxPHP
a variablelet name = "Ada"$name = "Ada"; (every variable starts with $)
joining text"Hi, " + name"Hi, " . $name (a dot, not a plus)
printingprint(...)echo ...; and it goes to the visitor, not your screen
reading inputinput("Name? ")$_GET['name'] and $_POST['name'], filled in before your code runs
a value that might be missingOptionnull, with ?? to supply a fallback
a recordstructan array with named keys: ['name' => 'Ada']
things that go wrongResultexceptions, or false from older functions
when types are checkedbefore runningwhen the line runs

The fourth row is where this article lives. Everything else carries over.

Your own web server, in one line

You need PHP itself. On Debian or Ubuntu, that’s:

sudo apt install php-cli

For macOS, Windows and everything else, php.net/downloads has instructions. Check that it worked with php -v.

Now make an empty folder, and in it a file called hello.php:

<?php
$name = "world";
?>
<h1>Hello, <?= $name ?>!</h1>

Two things in there are new. Anything between <?php and ?> is PHP code. Everything outside those tags is sent out as it is, with no processing at all. And <?= $name ?> is shorthand for “echo this value right here”.

In a terminal, from that folder, start PHP’s built-in web server:

php -S localhost:8000

localhost means “this computer”, and 8000 is a port, a numbered door on it that the server listens at. Open a browser and visit http://localhost:8000/hello.php. You’ll see a big “Hello, world!”

Now look back at the terminal. A few new lines appeared there, and one of them looks like this:

[Sun Nov 22 15:34:22 2026] [::1]:35704 [200]: GET /hello.php

That line is the server telling you it just ran your program for someone. Keep that terminal where you can see it. It’s the most useful window in this article.

Now try it. Change "world" to your own name, save the file, and refresh the browser. There’s no compile step and no restart. Every refresh runs your file again, from the top, with whatever you last saved.

The built-in server is a tool for your own machine. The PHP manual says it shouldn’t be used on a public network, and when you put a site online for real, a different server does this job. For learning, it’s all you need.

A conversation in two messages

When you refreshed that page, your browser and the server had a short conversation. It went like this.

The browser sent a request. A request is a small piece of text that says what the browser wants:

GET /hello.php HTTP/1.1
Host: localhost:8000

The first word is the method, which says what kind of request this is. GET means “please give me this”. Then comes the path, the part of the address after the server’s name. The lines after that are headers, labeled bits of extra information. A real browser sends a dozen or so headers, describing itself and what it can accept.

The server ran hello.php and sent back a response, which has the same shape:

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

<h1>Hello, world!</h1>

The first line holds a status code: 200 means everything went fine. You’ve met its cousin 404, which means “no such page”. Then come the response’s headers, then one blank line, then the body, which is the thing the browser shows you.

The rules for this conversation are called HTTP, the HyperText Transfer Protocol. A protocol is an agreement about who says what, in what order. HTTP has a lot of details, and the overview on MDN Web Docs, Mozilla’s reference for the web, is a friendly place to read them. But its heart is the two messages you just saw. One request in, one response out.

Every echo in your PHP file, and every bit of HTML outside the tags, becomes part of that response body. That’s what the shortcut table meant when it said echo goes to the visitor. Your program doesn’t talk to a screen. It writes a reply.

Your program lives for one request

Here’s the part that surprises people. Save this as count.php in the same folder:

<?php
$visits = 0;
$visits = $visits + 1;
?>
<p>This is visit number <?= $visits ?>.</p>

Visit http://localhost:8000/count.php and refresh it a few times. Watch the terminal: a new line for every refresh. Watch the page: visit number 1. Visit number 1. Visit number 1.

Of course it says 1. The program sets $visits to 0 and adds 1. But think about what that means. In most programs you’ve written, a variable lives as long as the program does, and a program lives until it’s done. This program is done well under a millisecond after each request arrives. The server reads the request, starts your file fresh at the first line, runs it to the end, sends whatever it printed, and throws away every variable you made. The next request gets a brand-new run that has never heard of the last one.

A program that keeps nothing from one request to the next is called stateless. State is whatever a program remembers: the values in its variables, the things it has counted, the stage it has reached. A PHP page starts every request with none.

If you learned lux, you know the opposite shape well. A lux program owns its whole run: it starts, asks questions with input(), keeps its variables while it loops, and ends when it decides to. A PHP page lives for one request and forgets everything. (If you ever wrote a lux file for a host, you’re halfway there. The host called your functions and kept what they handed back. A web server is a host that calls your page and keeps nothing.)

This isn’t a PHP quirk. HTTP itself was designed this way. Its specification calls it “a stateless protocol, meaning that each request message’s semantics can be understood in isolation.” Every request has to make sense on its own, because the protocol doesn’t count on the server remembering the one before. PHP takes that design and builds its programs to match.

What you need arrives with the request

If a program can’t remember anything, how does it know anything? It reads the request. Everything your page needs to do its job has to come in with the request or be fetched from somewhere while it runs.

The simplest place to carry information is the address itself. Try this as greet.php:

<?php
$name = $_GET['name'] ?? 'stranger';
?>
<h1>Hello, <?= htmlspecialchars($name) ?>!</h1>

Visit http://localhost:8000/greet.php and you’ll be greeted as a stranger. Now visit http://localhost:8000/greet.php?name=Ada. The bit after the ? is the query string, a list of names and values glued onto the address. PHP reads it before your code starts and puts it in $_GET, an array with a key for each name. Change the name in the address bar and press Enter. It’s the same edit and refresh, only this time you’re editing the request instead of the file.

$_GET is one of PHP’s superglobals: arrays that PHP fills in from the request before the first line of your file runs, and that every part of your program can see. There’s one for each part of the request you might care about.

The ?? says “use the left side if it exists and isn’t null, otherwise use the right side”. Without it, a visit with no query string would ask for a key that isn’t there. Requests come from strangers, and anything in one might be missing. (Some languages make you deal with missing values before your program will even run. The Rust article shows how; in PHP, ?? is your polite fallback.)

And htmlspecialchars is there for a reason that gets its own section below. For now, wrap it around anything that came from a request before you echo it.

Forms are requests you fill in

Typing a query string by hand gets old. A form is HTML that builds the request for you. The visitor fills in the fields, presses the button, and the browser sends a new request carrying what they typed. Put this in form.php:

<?php
$name = $_POST['name'] ?? '';
?>
<form method="post">
    <input name="name" value="<?= htmlspecialchars($name) ?>">
    <button>Send</button>
</form>
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST'): ?>
    <p>The server received: <?= htmlspecialchars($name) ?></p>
<?php endif; ?>

Load the page, type something, and press Send. In the terminal you’ll see two requests: first a GET /form.php that fetched the empty form, then a POST /form.php that sent it back filled in.

POST is the other common method. Where GET carries its values in the address, POST carries them in the request body, below the headers, where they don’t show up in the address bar or the browser’s history. The usual rule is that GET asks for something and POST changes something. A search is a GET. Signing up, paying, or leaving a comment is a POST. PHP puts posted values in $_POST, and $_SERVER['REQUEST_METHOD'] tells you which kind of request this run is answering.

Look at the input box after you press Send. It still holds what you typed. That isn’t the browser remembering, and it isn’t PHP remembering either. Your program read the posted name out of the request and wrote it back into the new page’s value. When a stateless program seems to remember something, this is usually how: the information came in with the request, and the program sent it back out.

Now press refresh on that page. Your browser asks whether you want to send the form again. That’s not a bug. The page you’re looking at was the answer to a POST, and refreshing means repeating the request that made it. The project below shows the standard way around this.

Where memory goes when the program can’t keep it

Real sites remember things: who you are, what’s in your cart, what everyone wrote yesterday. Since the program can’t hold any of it, the memory has to live somewhere outside the program. There are three places it can go.

It can ride in the request itself, as you just saw. A query string, a form field, or a hidden field (a form field the visitor doesn’t see) carries information from one page to the next. The catch is that the visitor’s browser holds it, and the visitor can change it.

It can live in a cookie. A cookie is a small named value the server asks the browser to keep. The server sends it in a response header, and from then on the browser sends it back in a header with every request to that site. Here’s the counter again, fixed:

<?php
$visits = (int) ($_COOKIE['visits'] ?? 0) + 1;
setcookie('visits', (string) $visits);
?>
<p>This is visit number <?= $visits ?>.</p>

Save it over count.php and refresh a few times. Now it counts. The program still forgets everything at the end of each run. The browser is doing the remembering, and handing the count back with each request. Open the same page in a private window and you start again at 1, because that window has its own cookies.

Notice where setcookie sits: at the very top, before any HTML. A cookie travels in a header, and headers come before the body in the response. Once your program has started writing the body, the headers have gone. Move the setcookie call below the <p>, inside its own <?php ?> tags, and start the server as php -d output_buffering=0 -S localhost:8000. Now PHP complains in the server’s terminal: Cannot modify header information - headers already sent. (Without that flag, many installs quietly hold back the first few kilobytes of the body in a buffer, so the late header still fits and you see no warning. Don’t count on it.) The shape of the response is showing through the language.

Or the memory can live on the server, in a file or a database. Each run reads what it needs when it starts and writes back what changed before it ends. This is the only place for things that belong to everyone rather than to one visitor. A cookie can count your visits, but it can’t count the site’s, because it lives in your browser and nobody else’s. The project uses a file.

(PHP also has sessions, which combine the last two: a cookie holds a random ID, and the server keeps the data under that ID. You’ll meet them soon after this article, and now you know what they’re made of.)

Why forgetting is a feature

At this point, statelessness might sound like a handicap that the web forces on you. It’s closer to the opposite.

Because each run starts clean, nothing piles up. A bug that corrupts a variable ruins one response, and the next request starts fresh. A crash takes down one visitor’s page, not the site. And because no run holds anything another run needs, a busy site can start many copies of the same program at once, even on different machines, and send each request to whichever copy is free. None of them needs to know what the others are doing. This design has a name, shared-nothing, and it’s why a PHP site can handle more visitors by adding more machines.

The price is the one you’ve been paying all along: you have to decide where every piece of state lives, and carry it there on purpose.

Once you know this shape, you’ll see it far beyond PHP. A web program in almost any language boils down to a function that takes a request and returns a response. Go, Python, Java and JavaScript on a server all hand you a request object and ask you for a response. In PHP, the whole file is that function.

The browser side of the conversation works differently. A page in the browser stays open and waits for clicks and keypresses, running a little code each time something happens. That’s event-driven programming, and the JavaScript article is its home. A PHP page never waits. It runs, answers, and ends.

Where PHP trusts you

PHP gives up two guarantees you may be used to.

The first is about types. PHP lets you declare them, but it checks them only when a line runs. A mistake in a branch that never runs stays quiet until the day it does. Turn on strict checking with the declare line at the top, and this stops with a TypeError the moment the call happens, not before:

<?php
declare(strict_types=1);

function shout(string $text): string {
    return $text . "!";
}

echo shout("ready"), "\n";
echo shout(42), "\n";

The first line prints ready!. The second line fails. For a web page, that means a request that takes an unusual path can find a mistake that every other request walked past. The introduction runs the same experiment across several languages.

The second is about text. PHP doesn’t know which text you wrote and which text a stranger typed. To PHP, $_GET['name'] is a string like any other, and if you echo it into the page, the browser treats it as part of your HTML. Someone who sends a “name” containing a <script> tag gets their code running on your page, in every visitor’s browser that shows it. This is called cross-site scripting.

htmlspecialchars is the fix. It escapes the characters that mean something in HTML, turning < into &lt; and so on, so the browser shows them as text instead of obeying them:

<?php
$name = "<script>alert('hi')</script>";
echo htmlspecialchars($name), "\n";

That prints &lt;script&gt;alert(&#039;hi&#039;)&lt;/script&gt;, which a browser shows as harmless text.

Beware of old tutorials that skip escaping and prepared statements. PHP has been around since the 1990s, and the web is full of PHP examples that echo $_GET straight into a page, or paste it straight into a database query. The second mistake is called SQL injection (SQL, Structured Query Language, is what databases speak), and the fix is a prepared statement, which sends the query and the visitor’s values to the database separately so the values can never become part of the command. Both mistakes look fine when you test them with your own name. Both become disasters when a stranger tests them for you. If a tutorial echoes request data without escaping it, or builds a query by gluing strings together, close the tab. It doesn’t matter how clear the rest of it is. There are plenty of tutorials that get this right.

A guestbook

Fittingly for a language that started with one, the project is a guestbook: a page where visitors leave their name and a message, and everyone sees what everyone wrote. It’s one file, projects/php/index.php. From that folder, run:

php -S localhost:8000

Then visit http://localhost:8000/. The server finds index.php on its own when the address names a folder, the way it would find index.html.

Sign the book. Leave the message empty and try again. Sign it once more with a message like <em>hello</em>. Then open the file, and keep the terminal in view while you read. The guestbook holds every kind of state from this article.

The entries live in a file. Each time someone signs, the program adds one line to guestbook.txt, a record encoded as JSON (JavaScript Object Notation, a common text format for structured data). Each time anyone loads the page, the program reads every line back. Nothing about the entries survives in the program between requests. They survive on disk, so everyone sees the same book.

Your name lives in a cookie. After you sign, the response sets a name cookie, and the next time you load the page, the program reads it back from $_COOKIE and fills in the name field for you. Open the page in a private window and the entries are all there, but your name isn’t. Different state, different home.

A mistake lives in the request. If you leave a field empty, the program doesn’t save anything. It answers with status code 400, “bad request”, and a page that contains your own words, read out of $_POST and written back into the form, so you don’t have to type them again. Nothing was remembered. Your words made the round trip.

Now sign once more and watch the terminal. One signature makes two requests:

[303]: POST /
[200]: GET /

The POST carried your signature. Instead of answering it with a page, the program answered with status 303, “see other”, plus a Location header pointing back at /. That tells the browser to go and fetch that address with a fresh GET, so the page you end up looking at is the answer to a harmless GET. Refresh it as often as you like; nothing is sent twice. This pattern is called Post/Redirect/Get, and it’s how most sites keep a refresh from paying for something twice.

Find the <em>hello</em> you signed with. It shows up as text, angle brackets and all, because the program passes everything a visitor wrote through e(), a one-line function wrapped around htmlspecialchars. Every value that came from a request goes through it on the way out.

At the bottom of the page is the time it was built. Refresh, and it changes. Every page you see is a new answer to a new request, written a moment ago by a program that has already stopped running.

The end of index.php has a list called “Try this next…” with more experiments. The first one shows you what the browser does when Post/Redirect/Get goes missing.

What’s left out, and where to go next

This article left out a lot of PHP. There’s nothing here about databases (PHP’s built-in way to reach them is called PDO, PHP Data Objects, and it does prepared statements well), sessions beyond a paragraph, classes, Composer (PHP’s tool for using other people’s packages), or frameworks like Laravel and Symfony. Nothing either about how PHP runs on a real server, where a production web server hands requests to PHP instead of php -S doing it all. Every one of those is built on the request and response you just learned, so none of them should feel like magic when you meet them.

The PHP manual is the place to go next. It’s at php.net/manual, it has a short tutorial of its own, and every function page ends with notes and examples. When you want to know what a superglobal holds, its page in the manual will tell you.

See what the browser saw

Load your guestbook in the browser, right-click the page and choose View Page Source. (Safari shows that item once its developer features are turned on in its settings.) Bring this question with you: where did the PHP go?

  • JavaScript: event-driven programming, the browser’s side of the conversation.
  • Rust: values that might be missing, and a language that makes you handle them before it runs.
  • The introduction: when types are checked, with the same experiment in five languages.

Tested with PHP 8.4.28, November 2026.