What is PHP and How It Runs
Explain what PHP is, how a PHP script executes on a server through the Zend Engine, and write and run a first PHP file using both the CLI and basic output/debugging functions.
PHP is a server-side scripting language purpose-built for the web: it generates HTML, talks to databases, handles forms, and powers a huge share of the internet, from small personal sites to platforms like Facebook and Wikipedia. Unlike client-side JavaScript, PHP code never reaches the visitor's browser — it runs on the server, produces output (usually HTML, JSON, or plain text), and that output is what gets sent down the wire. This lesson covers what PHP actually is, how it executes under the hood, and the handful of commands and syntax markers you'll use in every PHP file you ever write.
PHP as a Server-Side Language
PHP ("PHP: Hypertext Preprocessor", a recursive acronym) is an open-source, general-purpose scripting language that was designed specifically for web development but can also be used for command-line scripting and, less commonly, desktop applications. It is a server-side language, which means the PHP interpreter runs on the web server, executes your .php file, and produces an output — typically HTML — that gets sent to the client's browser. The visitor never sees your PHP source code, only whatever the script printed.
This is fundamentally different from JavaScript running in a browser. JavaScript in the browser manipulates a page that has already arrived; PHP on the server decides what page arrives in the first place. A single PHP script can query a database, loop over the results, and stitch together an entire HTML page before the browser has received a single byte. This request-driven, generate-then-send model is the core mental model for everything else in PHP.
PHP was created by Rasmus Lerdorf in 1994 as a set of Common Gateway Interface (CGI) binaries written in C, originally just to track visits to his online resume — hence "Personal Home Page Tools", the original meaning of the acronym. It has since gone through major versions (PHP 3, 4, 5, 7, and the current PHP 8.x line) that each brought large performance and language improvements. PHP 7 in particular roughly doubled performance over PHP 5 thanks to a new engine implementation, and PHP 8 added a JIT (Just-In-Time) compiler along with modern language features like union types, named arguments, and attributes.
• PHP = Hypertext Preprocessor, a server-side scripting language for the web. • Server-side: code runs on the server; only the output (e.g. HTML) reaches the browser. • Created by Rasmus Lerdorf in 1994; now maintained by a large open-source community. • Major eras: PHP 5 (widely deployed legacy), PHP 7 (big performance leap), PHP 8.x (JIT, modern typing) — this course targets PHP 8.x.
The Zend Engine and How a Script Runs
The Zend Engine is the core interpreter that powers PHP. When you run a PHP file, the engine goes through several stages: lexing (breaking source text into tokens), parsing (turning tokens into an abstract syntax tree), compiling that tree into opcodes (a low-level bytecode-like representation), and finally executing those opcodes on the Zend virtual machine. Extensions like OPcache can cache the compiled opcodes between requests so PHP doesn't have to re-parse and re-compile the same file on every single request, which is a major performance win in production.
PHP can be invoked in a few different ways. The PHP CLI (Command-Line Interface) runs the php binary directly against a script from a terminal — useful for scripts, cron jobs, and tooling like Composer. PHP-FPM (FastCGI Process Manager) is a fast, robust way to run PHP as a pool of worker processes that a web server hands requests to; it's the standard way to run PHP behind Nginx, and is also commonly used behind Apache. Apache can also embed PHP directly as a module (mod_php), which is simpler to set up but less flexible and less resource-efficient than FPM.
The full request lifecycle for a typical PHP web app looks like this: a browser sends an HTTP request to a web server (Apache or Nginx); the web server recognizes the request targets a .php file and hands it off to the PHP process (via mod_php or, more commonly today, via FPM over FastCGI); PHP executes the script from top to bottom, building up an output buffer; PHP hands that output back to the web server; the web server sends it back to the browser as the HTTP response body. This entire cycle happens fresh on every request unless something (like OPcache or an external cache) short-circuits part of it.
• Zend Engine: lexes, parses, compiles to opcodes, and executes PHP source code. • OPcache: caches compiled opcodes across requests to avoid re-compiling on every hit. • PHP CLI: runs scripts directly from the terminal via the php binary. • PHP-FPM: a process manager that serves PHP requests efficiently behind Nginx or Apache. • Request lifecycle: browser → web server → PHP (FPM/module) → script executes → output → web server → browser.
PHP File Syntax: Tags, Statements, Comments
A PHP file usually has the .php extension and can freely mix plain HTML with PHP code. PHP code is marked off from surrounding HTML using tags: <?php opens a PHP block and ?> closes it. Everything between those tags is parsed as PHP; everything outside them is passed straight through as literal text (typically HTML). There is also a short echo tag, <?=, which is shorthand for <?php echo — extremely common in view/template files because it's more compact.
Every PHP statement ends with a semicolon ;, the same way it does in JavaScript, C, or Java. Whitespace (spaces, tabs, newlines) between tokens is not significant to the parser — you can format code however is most readable — but whitespace inside string literals is preserved exactly as written. PHP files should be saved as UTF-8 without a byte-order mark (BOM); a stray BOM at the top of a file is a classic cause of "headers already sent" errors because it counts as output before your first <?php tag.
PHP supports three comment styles: // and # for single-line comments, and /* ... */ for multi-line block comments. Comments are stripped entirely before execution and have zero runtime cost. It's conventional in most PHP style guides (like PSR-12) to prefer // over # for single-line comments.
• <?php ... ?> — the standard opening/closing tags for a block of PHP code. • <?= $value ?> — short-echo tag, equivalent to <?php echo $value; ?>. • Every statement ends in ;. • Comments: //, # (single line), /* */ (multi-line) — all stripped before execution. • Save files as UTF-8 without BOM to avoid subtle output/header bugs.
Output and Debugging: echo, print, var_dump, print_r, var_export
echo and print both send text to the output buffer. echo is a language construct (not a real function) that can take multiple comma-separated arguments and returns no value; print takes exactly one argument, returns 1, and can be used inside expressions. In practice echo is used almost everywhere because it's marginally faster and more flexible.
For debugging, PHP gives you three complementary tools. var_dump() prints a value's type and content in full detail, including array/object structure and string lengths — it is the most information-dense and the one most PHP developers reach for first. print_r() produces a more human-readable, less type-explicit representation, which is handy for quickly eyeballing arrays. var_export() outputs a string of valid PHP code that would recreate the value — useful for generating cache files or copy-pasting a literal back into source code. All three accept an optional second true argument (except var_dump) or, in var_dump's case, can be wrapped in output buffering, to capture the output as a string instead of printing it directly.
• echo "text"; — outputs text; accepts multiple comma-separated arguments. • print("text"); — outputs text; single argument; returns int(1). • var_dump($x); — type + value + structure, most detailed, best for debugging. • print_r($x); — human-readable structure, good for quick array/object inspection. • var_export($x); — outputs valid PHP source code representing the value.
A Minimal PHP File
declare(strict_types=1); must be the very first statement in a file if used; it changes how type declarations are enforced (covered in a later lesson). PHP_EOL is a portable newline constant (\n on Unix, \r\n on Windows). A file doesn't need a closing ?> if it ends in pure PHP — omitting it avoids accidental trailing whitespace/output bugs.
<?php
// Everything inside <?php ... ?> is executed as PHP.
declare(strict_types=1);
$name = "SampleApp";
echo "Hello, " . $name . "!" . PHP_EOL;
?>
<!-- Outside the tags, this is plain HTML, passed straight through -->
<p>The short echo tag: <?= $name ?></p>Code Examples
Running a PHP script from the terminal invokes the CLI SAPI (Server API) of PHP, which executes the file top to bottom and prints anything sent to standard output — no web server involved. Expected result: Hello from PHP CLI!
PHP tags can be opened and closed multiple times within one file, letting you drop into and out of PHP mode to interleave dynamic logic with static markup — this is the classic way PHP templates were (and often still are) written. The web server sends the browser only the rendered HTML — the <?php ... ?> block and the PHP source itself are never visible to the client.
Each debugging function is suited to a different purpose: var_dump shows precise types and lengths (ideal when you're unsure whether a value is a string "30" or an int 30), print_r is quick and readable, and var_export produces copy-pasteable PHP code. Expected result: array(3) { ["name"]=> string(3) "Ada" ["age"]=> int(30) ["active"]=> bool(true) } --- Array ( [name] => Ada [age] => 30 [active] => 1 ) --- array ( 'name' => 'Ada', 'age' => 30, 'active' => true, )
$ cat hello.php
<?php
echo "Hello from PHP CLI!" . PHP_EOL;
$ php hello.php<!DOCTYPE html>
<html>
<body>
<h1>Product List</h1>
<?php
$products = ["Keyboard", "Mouse", "Monitor"];
foreach ($products as $product) {
echo "<li>{$product}</li>";
}
?>
</body>
</html><?php
$user = ["name" => "Ada", "age" => 30, "active" => true];
var_dump($user);
echo "---\n";
print_r($user);
echo "---\n";
var_export($user);PHP Request Lifecycle
Every request re-runs the script (unless cached); PHP's job is to turn a request into output the web server can send back.
Browser Web Server PHP (FPM/module)
┌─────────┐ HTTP req ┌───────────┐ hands off ┌──────────────┐
│ GET / │ ──────────▶│ Nginx / │ ──────────▶│ Zend Engine │
│ index.php│ │ Apache │ (FastCGI) │ runs script │
└─────────┘◀────────────└───────────┘◀───────────└──────────────┘
▲ HTML response script output (echo/print)Important Rules
Always close every PHP statement with a semicolon.
Prefer echo for output in normal code; use print only when you need its expression-return behavior.
Reach for var_dump() first when debugging an unfamiliar value — it never hides type information.
Save all PHP source files as UTF-8 without a BOM.
Never leave debugging output (var_dump, print_r) in production code paths.
Where PHP Runs in Production
Large-scale sites like Wikipedia and much of WordPress-powered hosting run PHP behind Nginx with PHP-FPM pools tuned per traffic pattern, with OPcache enabled so scripts are compiled once and reused across thousands of requests per second, keeping response times low even under heavy load.
echo "Total: " . $price echo "Done";
echo "Total: " . $price . PHP_EOL; echo "Done" . PHP_EOL;
Missing the semicolon after the first echo is a parse error in PHP — every statement must end with ;, unlike some scripting languages where it's optional.
<? echo "hi"; ?> <?php echo "hi"; ?> The bare short-open tag <? (as opposed to <?=) depends on a php.ini setting (short_open_tag) that is often disabled; always use the full <?php tag for portability.
Where does PHP code actually execute? A. In the visitor's web browser, like JavaScript B. On the web server, before the response is sent to the browser C. Inside the database engine D. It doesn't execute; it's copied directly into the HTML
B. On the web server, before the response is sent to the browser — PHP is a server-side language: the server executes the script and only the resulting output (usually HTML) is sent to the browser.
[multiple-choice] Which function is best for seeing the exact data type and length of a value while debugging? A. print B. echo C. var_dump D. print_r
C. var_dump — var_dump() reports precise type information (e.g. int(30) vs string(2) "30") plus lengths and structure, making it the most detailed debugging tool of the group.
What is the short echo tag equivalent to? A. <?php print_r(...); ?> B. <?php echo ...; ?> C. <?php var_dump(...); ?> D. <?php comment ...; ?>
B. <?php echo ...; ?> — <?= $value ?> is exact shorthand for <?php echo $value; ?>, commonly used in template/view files.
Write a PHP CLI script named greet.php that declares a variable $language = "PHP", uses echo to print "Learning <language> on SampleApp", then uses var_dump() to inspect the $language variable.
<?php $language = "PHP"; echo "Learning {$language} on SampleApp" . PHP_EOL; var_dump($language);
Remember to open with <?php, end each statement with a semicolon, and concatenate strings with the dot (.) operator.