Introduction to PHP

Introduction to PHP in PHP: Walk into a small print shop on a busy street. Behind the counter is a drawer of master forms: an invoice, a delivery note, a…

The Analogy: The Jobbing Print Shop Behind The Counter

Walk into a small print shop on a busy street. Behind the counter is a drawer of master forms: an invoice, a delivery note, a membership certificate, a raffle ticket. Not one of them is finished. Each has blanks -- a name here, a date there, a total in the box at the bottom -- and beside the blanks, written in red pencil, are instructions to the clerk: look this customer up in the ledger, add the line items, work out the tax, print the total in the box. When somebody asks for an invoice, the clerk pulls a fresh copy of the master, carries out every red-pencil instruction, writes the results into the blanks in black ink, and hands one finished sheet across the counter. The customer never sees the red pencil. They see a document that looks as though it was typeset for them personally, and in every way that matters, it was.

That is PHP, almost line for line. The master form is a .php file sitting on the server's disk. The red-pencil instructions are the parts of that file between <?php and ?>. The black ink is anything the file prints. The counter is the web server, and the finished sheet is the HTTP response that reaches the browser. This is why PHP is described as a server-side, embedded language: the code is embedded inside the document it produces, and it is carried out on the server, so the person holding the finished sheet has no way to read the instructions that made it. Change the master form and the very next customer gets the new wording, with nothing to recompile and nothing to restart.

The second half of the analogy is the part beginners are never told, and it explains most of their early confusion. After each customer walks away, the clerk sweeps the desk completely: scrap paper in the bin, pencil marks erased, the counter clear for whoever is next. Nothing carried in the clerk's head survives into the following job. If information has to outlive one customer -- a running total, a member's login, last month's report -- it must be written somewhere deliberate: the ledger in the back office (a database), a numbered pigeonhole (a session file), a noticeboard everyone can read (a cache). PHP works the same way and the property has a name, shared-nothing. Every request begins with a clean interpreter, runs, prints, and is torn down. That is why a PHP page cannot leak a variable into the next visitor's page, why one crashed request cannot poison the ones after it, and why putting a second server behind a load balancer is almost boring: no request has ever depended on the machine that served the one before.

The failure mode is instructive, and it has two shapes. The first is a clerk who copies the customer's own words straight into the black ink. Somebody fills in the name field with a line that itself looks like an instruction, the finished sheet is read by a machine downstream -- a browser, a database, a shell -- and that machine cheerfully carries out the customer's words as though the shop had written them. Every injection vulnerability in existence is this one mistake, which is why the rule in this course is to escape at the moment of handing over, in the form the destination requires, and never once on the way in. The second shape is a clerk who assumes the desk was swept when it was not: a value parked in a global, a static property, or a stale configuration file survives into the next job, and one customer's total ends up printed on another customer's invoice. PHP's per-request teardown makes that rare, but long-lived worker processes and cached configuration bring it straight back, and it is always discovered by the customer rather than by the shop.


Syntax or Core Structure

A PHP file is a text file that the interpreter copies to the output verbatim until it meets an opening tag. Everything from <?php to the matching ?> is code; everything outside those tags is data. That single rule is the whole language model.

<?php
declare(strict_types=1);

echo "Hello from the print shop", PHP_EOL;

$visits = 1;
$visits = $visits + 1;

echo "You have been served {$visits} times", PHP_EOL;
printf("%s scored %d%% on %s\n", "Ada", 93, "the practical");
print "print returns a value, echo does not" . PHP_EOL;

Output:

Hello from the print shop
You have been served 2 times
Ada scored 93% on the practical
print returns a value, echo does not

Five things in that short file are worth naming, because they recur in every lesson of the course. declare(strict_types=1); must be the first statement in the file and switches the current file from coercive to strict parameter checking -- it is the difference between a function that quietly accepts "7" where it asked for an int and one that refuses. Variables begin with $ and are never declared with a type keyword. echo is a language construct rather than a function, which is why it can take a comma-separated list and why you cannot pass it to something else as a callback; print is also a construct but evaluates to 1, so it can sit inside an expression. PHP_EOL is the platform's line ending, and printf formats with the same conversion specifiers as C, where %% is how you print a literal percent sign.

Interpolation is where PHP's double-quoted strings earn their keep. "served {$visits} times" substitutes the variable's value; the braces are optional for a plain variable but required the moment you touch an array element or an object property, and using them everywhere costs nothing and prevents a whole family of parsing surprises. Single quotes do no interpolation at all: '{$visits}' prints those exact eight characters. When you want the dollar sign itself inside a double-quoted string, escape it as \$.

The embedded form is the other half of the model, and it is what the print shop analogy is really about:

<?php
$member = "Grace Hopper";
$expires = "2027-03-01";
?>
<article>
  <h1>Membership card</h1>
  <p>Issued to <?= htmlspecialchars($member) ?>, valid until <?= $expires ?>.</p>
</article>

Output:

<article>
  <h1>Membership card</h1>
  <p>Issued to Grace Hopper, valid until 2027-03-01.</p>
</article>

<?= is shorthand for <?php echo, it has been available unconditionally since PHP 5.4, and it is the only short tag that is always enabled. Two details in that output are easy to miss. PHP swallows exactly one newline immediately after a closing ?>, which is why the blank line you might expect between the tag and <article> is not there. And htmlspecialchars is doing the escaping-at-handover job from the analogy: with a member called Ada <script> the raw name would have been handed to the browser as markup, and the escaped version is handed over as text.


Technical Depth: What Happens Between The Request And The Page

The lifecycle, stage by stage

"PHP runs the file" hides about seven distinct steps, and knowing them is the difference between guessing at a bug and locating it.

StageWho does itWhat exists when it finishes
Connection acceptedthe web server, nginx or Apachea parsed HTTP request and a matched location block
Static or dynamic decisionthe web servereither a file streamed straight from disk, or a decision to call PHP
HandoffFastCGI protocol over a socketthe request headers and body sitting in PHP's input buffers
Worker selectedPHP-FPM's process managerone worker process, dedicated to this request alone
Compile or reusethe Zend engine plus OPcacheopcodes for every file the request touches, cached for later requests
Executethe Zend virtual machineoutput in a buffer, headers pending, plus any side effects on disk or in the database
TeardownPHP-FPMthe response flushed, every variable destroyed, the worker clean and idle again

The two rows people misread are the fifth and the last. Compilation is per file and cached, so the second request for a page is dramatically cheaper than the first -- that is what OPcache is, and it is the single largest performance setting in PHP. And teardown is total: memory is released, open handles are closed, and no variable from this request is visible to the next. When somebody says "my $_SESSION value disappeared", they have run into the last row and the fix is to store the value somewhere that outlives a worker, not to hunt for the variable.

Where PHP is running: the SAPI

The same interpreter is embedded in several hosts, and the host changes the rules more than beginners expect. The host is called a SAPI, a server API.

SAPIWhere you meet itProcess model
fpm-fcgiproduction traffic behind nginx or Apachea pool of long-lived workers, each handling one request at a time
apache2handlerolder shared hosting, the classic mod_phpthe interpreter is embedded in each Apache child process
cliComposer, PHPUnit, cron jobs, queue workersone fresh process per invocation, no HTTP headers, no execution time limit by default
cli-serverphp -S localhost:8000 for local experiments onlya single process that serves one request at a time, with no concurrency and no hardening
worker runtimesFrankenPHP, RoadRunner, Swoolethe process survives many requests, so shared-nothing stops being free and globals become a real hazard

php_sapi_name() returns which one you are in, and it is the honest way to write a script that must behave differently on the command line than it does in a browser.

Versions, and the support window that actually matters

VersionReleasedHeadline change
5.62014the last of the old engine; variadics and constant expressions
7.02015a rewritten engine, roughly double the throughput, scalar type declarations, the ?? operator
7.42019typed properties, arrow functions, preloading
8.02020JIT, union types, named arguments, match, constructor promotion, attributes, saner string-to-number comparison
8.12021enums, readonly properties, fibers, first-class callable syntax
8.22022readonly classes, disjunctive normal form types, dynamic properties deprecated
8.32023typed class constants, json_validate, the Override attribute
8.42024property hooks, asymmetric visibility, lazy objects, array_find and friends
8.52025a pipe operator spelled as a bar followed by a greater-than sign, array_first and array_last, backtraces on fatal errors

The release train leaves every November, and each version gets two years of active support followed by two years of security fixes only. At the time of writing that means 8.1 and everything older is finished, 8.2 and 8.3 receive security patches and nothing else, and 8.4 and 8.5 are the versions to target for new work. This course assumes 8.1 or newer and points out anything that needs 8.2, 8.3, or 8.4 where it appears.

The seven settings that decide your day

PHP reads a php.ini file at startup, and a handful of its directives cause most of the surprises in a beginner's first month.

DirectiveDevelopmentProductionWhy it matters
display_errorsOnOffan error printed into a live page leaks file paths, query shapes, and sometimes credentials
log_errors with error_logOn, to the terminalOn, to a file or syslogswitching display off is only safe if the error still lands somewhere you read
error_reportingE_ALLE_ALLyou want the undefined-index warning recorded even when nobody is looking at the page
opcache.enableon, with timestamp validationon, with validation off and a reset at deploythe difference between recompiling every file on every request and not
memory_limitgenerous, so you see real dataas small as the work needsone runaway request should not be able to starve the others
max_execution_time30 seconds30 or less for web requeststhe CLI SAPI ignores this and runs until stopped, which is why cron jobs need their own guard
date.timezoneUTCUTCstore and calculate in UTC and convert only when printing, or daylight saving will eventually corrupt a report

Editing php.ini does nothing until the SAPI restarts, and that catches everyone once: with PHP-FPM you must reload the pool, because the workers read the file when they start. php --ini prints which files were actually loaded, which is the fastest way to discover you have been editing the CLI copy while your web requests use another.

Facts about the engine you can check in ten seconds

<?php
declare(strict_types=1);

echo 2 ** 10, PHP_EOL;
echo intdiv(7, 2), " and ", 7 % 3, PHP_EOL;
echo 10 <=> 2, PHP_EOL;
var_dump(0.1 + 0.2 === 0.3);
var_dump(PHP_INT_MAX);
var_dump(PHP_INT_SIZE);
var_dump("10" == "1e1");
var_dump("abc" == 0);
echo php_sapi_name(), PHP_EOL;

Output:

1024
3 and 1
1
bool(false)
int(9223372036854775807)
int(8)
bool(true)
bool(false)
cli

Two of those lines are build-dependent and are labelled as such: PHP_INT_MAX and PHP_INT_SIZE show the values from a 64-bit build, which is what you will almost certainly have, and a 32-bit build would print 2147483647 and 4. The rest are guaranteed. 0.1 + 0.2 === 0.3 is false because binary floating point cannot represent those decimals exactly, which is the reason money is handled as integer minor units throughout this course. "10" == "1e1" is true because two numeric strings are compared as numbers, and both are ten. "abc" == 0 is false, and that is a PHP 8 change: before 8.0 the string was converted to 0 and the comparison was true, which quietly broke countless authorisation checks. Finally php_sapi_name() prints cli here because the script was run as php lesson.php; the same file behind nginx would print fpm-fcgi.


Real World Example: Printing A Job Ticket For The Shop

The print shop needs a ticket for the bench: what was ordered, what each line costs, and what the customer owes. This is the shape of a real first PHP program -- read a small structure, calculate, format, print -- and it makes one decision that will matter for the rest of the course.

<?php
declare(strict_types=1);

function jobLine(string $label, int $qty, int $unitPence): array
{
    return ['label' => $label, 'qty' => $qty, 'unit' => $unitPence, 'total' => $qty * $unitPence];
}

function pounds(int $pence): string
{
    return number_format($pence / 100, 2);
}

$ticket = 4471;
$customer = "Whitcomb & Sons";
$lines = [
    jobLine("Business cards, 250", 2, 1850),
    jobLine("A3 poster, matte", 3, 725),
    jobLine("Spiral binding", 1, 450),
];

$subtotal = 0;
foreach ($lines as $line) {
    $subtotal += $line['total'];
}
$vat = (int) round($subtotal * 0.20);
$total = $subtotal + $vat;
$rule = str_repeat("-", 47);

echo "CORNER PRINT SHOP -- job ticket {$ticket}\n";
echo "Customer: {$customer}\n";
echo $rule, "\n";
foreach ($lines as $line) {
    printf("%-24s %2d x %6s = %8s\n", $line['label'], $line['qty'], pounds($line['unit']), pounds($line['total']));
}
echo $rule, "\n";
printf("%-24s %22s\n", "Subtotal", pounds($subtotal));
printf("%-24s %22s\n", "VAT at 20%", pounds($vat));
printf("%-24s %22s\n", "Total due", pounds($total));
echo $rule, "\n";
printf("%d lines, %d items in total\n", count($lines), array_sum(array_column($lines, 'qty')));

Output:

CORNER PRINT SHOP -- job ticket 4471
Customer: Whitcomb & Sons
-----------------------------------------------
Business cards, 250       2 x  18.50 =    37.00
A3 poster, matte          3 x   7.25 =    21.75
Spiral binding            1 x   4.50 =     4.50
-----------------------------------------------
Subtotal                                  63.25
VAT at 20%                                12.65
Total due                                 75.90
-----------------------------------------------
3 lines, 6 items in total

The decision worth arguing about is on the third line: every price is an integer number of pence, and pounds() divides by a hundred exactly once, at the moment of printing. The engine facts above showed why. Floating point cannot hold 0.1 or 18.50 exactly, so a total built by adding floats drifts, and an invoice that is one penny out is a support call, an accounting reconciliation, and a loss of trust in the software. Integers do not drift. This is the single most transferable habit in the lesson: money is a whole number of the smallest unit, and the division happens at the edge, on the way to a human.

The formatting comes from printf, which uses the same conversion specifiers as C. %-24s means "a string, left-aligned, padded to at least 24 characters"; drop the minus and it right-aligns, which is what %6s and %8s do for the money columns. The widths were chosen so that every line is exactly 47 characters wide and the equals signs sit in the same column, which is why str_repeat("-", 47) produces a rule that matches the table instead of a rule of some hopeful length. Note that pounds() returns a string, so the money columns use %s rather than %f: the formatting has already happened, and asking printf to format it again would undo the thousands separators. %% in the VAT label is the only way to print a literal percent sign inside a format string.

The data structure is the one you will meet in nine out of ten PHP codebases: an associative array for each record, and a plain indexed array of those records for the table. $line['label'] reads like the invoice column it prints, which is worth more than it sounds when the loop is thirty lines long instead of one. foreach ($lines as $line) hands you a copy of each record; PHP's copy-on-write means that copy costs nothing until you modify it, so this is cheap rather than wasteful. array_column($lines, 'qty') plucks one field out of every record into a flat array, array_sum adds them, and count reports how many records there were. In a larger program each record would become a class with typed properties, which is exactly where the OOP module of this course begins -- but reaching for a class on day one, before the shape of the data has settled, is how beginners end up with fifteen files and no working ticket.

Now the honest part, because a working program is not a good one. The VAT line is a genuine design flaw: an all-integer money design is broken open by (int) round($subtotal * 0.20), which multiplies an integer by a float and then rounds, exactly the arithmetic the rest of the program was written to avoid. intdiv($subtotal * 20, 100) stays in integers and states its rounding rule out loud, and it matters that the rule is stated, because PHP's round() rounds halves away from zero while several tax authorities require half-even. A second real flaw sits beside it: a single rate is applied to the whole subtotal, so a ticket mixing standard-rate posters with zero-rated books cannot be represented at all, let alone taxed correctly -- the rate belongs on each line, not on the invoice. Third, nothing here is escaped, and the moment this output moves from a terminal to a web page Whitcomb & Sons is malformed HTML that should read Whitcomb &amp; Sons, while a customer named with a script tag would be handed to the browser as code. The remaining weaknesses are rough edges rather than flaws: a label longer than 24 characters pushes the columns out because printf pads but never truncates, number_format always uses English separators regardless of the reader's locale, and the currency itself is never recorded anywhere, so nothing in the file says these are pence rather than cents.


Common Mistakes

  1. Leaving a closing ?> at the end of a pure-PHP file. Every byte after that tag is output, including the newline your editor helpfully adds. Once output has begun PHP cannot send headers, so a redirect or a cookie set later fails with "headers already sent" and points at a line that looks blameless. In files that contain only code, omit the closing tag entirely.
  2. Copying <? from an old tutorial. The two-character short tag depends on the short_open_tag directive and is off in most modern configurations, so your code is served to the browser as text -- which is how source code and sometimes credentials end up published. Write <?php, and use <?= for output, which is always enabled.
  3. Escaping on the way in instead of on the way out. Running htmlspecialchars on $_POST at the top of the script corrupts the stored value and still gets the escaping wrong, because the correct escape depends on the destination: HTML wants htmlspecialchars, SQL wants a prepared-statement placeholder, a URL wants urlencode, and a shell wants escapeshellarg. Store what the user typed; escape at each handover.
  4. Reading == as "equals". It compares after type conversion, and even with PHP 8's improved rules "1e3" == "1000" and null == 0 are both true. Default to ===, which compares type and value, and use == only when you can say out loud which conversion you are relying on.
  5. Expecting a variable to survive to the next request. The page you just rendered no longer exists anywhere; the worker that built it has been wiped. Anything that must outlive one request goes into a session, a cookie, a cache, or the database, and each of those is a deliberate line of code rather than a default.
  6. Assuming $_GET and $_POST contain the keys you expect. A missing key raises a warning and evaluates to null, which then travels quietly through your logic. Write $page = (int) ($_GET['page'] ?? 1); so the default and the type are both visible at the point of reading.
  7. Editing the wrong php.ini, or the right one without reloading. The CLI and FPM SAPIs commonly read different files, and FPM workers only read theirs at startup. php --ini prints the file the command line uses; the running web configuration is what phpinfo() reports, and a change to it needs a pool reload.
  8. Developing with display_errors off. A blank white page is PHP telling you something it would gladly have explained in one line. Turn errors all the way up in development and turn display off with logging on in production; the mistake is having both off anywhere.
  9. Storing money in a float. 0.1 + 0.2 === 0.3 is false, and a running total accumulated in floats drifts by fractions of a penny that eventually surface as a mismatched invoice. Use integer minor units, or a dedicated decimal library, and format once at the edge.

Best Practices

  • Target a supported version and pin it in three places. Put a constraint such as "php": "^8.3" in composer.json, name the same version in your CI matrix, and pin the container image tag. A version that exists only in a README is a version somebody will contradict.
  • Open every file with declare(strict_types=1);. It is per file, not per project, so a single missing line silently restores coercive mode for that file. With it on, a function that asks for int refuses "7" instead of quietly converting, which turns a class of production surprises into a development error.
  • Escape at the handover, in the form the destination requires. htmlspecialchars for HTML, placeholders for SQL, urlencode for query strings, escapeshellarg for a command line, json_encode for JSON. The value in your variables should always be the real value the user gave you.
  • Keep configuration in the environment and secrets out of the repository. Read credentials from environment variables, keep a committed .env.example with the keys and no values, and make the application fail loudly at startup when a required variable is missing rather than at midnight when it is first used.
  • Set error_reporting to E_ALL everywhere and change only where the errors go. Display them in development, log them in production. Suppressing a warning with @ hides the one line that explains the bug and costs you an hour later.
  • Use Composer from the very first file, even with no dependencies. composer init plus a PSR-4 autoload entry means you never write a chain of require statements, and it puts your project in the same shape as every library you will later install.
  • Integers for money, UTC for time. Store minor units and format at the edge; store timestamps in UTC and convert when printing. Both mistakes are cheap to avoid on day one and expensive to unpick after a year of stored data.
  • Let tools read your code before a human does. php -l catches syntax errors without running anything, a static analyser such as PHPStan finds the type mistakes the runtime never reaches, and reading the manual page for each function the first time you use it is worth the minute -- PHP's standard library is famously inconsistent about argument order, with in_array(needle, haystack) beside strpos(haystack, needle).

Practice Exercises

  1. Install, then find out what you installed. Get PHP 8.3 or newer running, then run php --ini and write down every file it reports loading. Now run a one-line script that prints php_sapi_name() from the command line, and serve the same file with php -S localhost:8000 and load it in a browser. Explain why the two runs print different words.
  2. Break the closing tag on purpose. Write a file that ends with ?> followed by a blank line, and after that tag attempt to send a header with header("Location: /next.php");. Read the exact error, then delete the closing tag and confirm the redirect works. Write two sentences explaining what the newline had to do with it.
  3. Extend the job ticket to mixed VAT rates. Give each line its own rate of 0 or 20 percent, compute the tax per line with intdiv so no float appears anywhere, and print a tax column plus separate zero-rated and standard-rated subtotals. Verify the totals by hand for a ticket containing one zero-rated and two standard-rated lines before you trust the program.
  4. Move the ticket to the web, safely. Wrap the output in an HTML table, print every customer-supplied value through htmlspecialchars, then set the customer name to the literal text Whitcomb & Sons <script>alert(1)</script> and view the page source. Confirm the ampersand and the tag appear as escaped text, then explain in your own words why escaping at output rather than on input is what made that possible.