The Request-Response Cycle
When you request a .php file, here is what happens:
1. Browser sends HTTP request: GET /hello.php HTTP/1.1 2. Web server receives request, sees .php extension 3. Server invokes PHP interpreter to execute the script 4. PHP runs the code, collecting all output (echo, print, HTML outside tags) 5. Server wraps output in HTTP response: HTTP/1.1 200 OK Content-Type: text/html Hello, World! 6. Browser displays the response
Unlike Node.js, where you write the server yourself, PHP runs inside an existing web server like Apache or nginx. The server detects the .php extension and hands the file to the PHP interpreter automatically.
The Simplest PHP Script
That's it. The <?php tag starts PHP mode, echo outputs text, and ?> ends PHP mode.
Mixing PHP and HTML
PHP was designed as a templating language. You can freely mix PHP code with HTML markup:
Current time: = date('H:i:s') ?>
- HTML outside
<?php ?>passes through unchanged <?= ... ?>is shorthand for<?php echo ... ?>- PHP is essentially a templating language at heart
Stateless Execution
This is one of the most important concepts in PHP: every request starts fresh.
- New PHP process (or thread) is created
- Script executes from the beginning
- All variables are created anew
- Response is sent
- Everything is discarded
This is why we need sessions (covered in a later tutorial) to maintain state between requests. Compare this with Node.js, where the process runs continuously and variables persist in memory.
Try This
- View hello.php and note what appears in the browser
- View templating.php and refresh several times — watch the time change
- Right-click and "View Page Source" to see that no PHP code appears in the output
- Try modifying the files and refreshing to see changes immediately
Summary
- PHP scripts run on the server inside Apache or nginx — the browser never sees PHP code
<?php ... ?>starts and ends PHP mode;<?= ?>is shorthand for echo- HTML outside PHP tags passes through unchanged, making PHP a natural templating language
- Each request starts a fresh PHP process — no state carries over between requests