What PHP Actually Does
PHP is a programming language that runs on a web server. That one sentence explains nearly everything that confuses beginners about it. When a browser opens an ordinary HTML file, the browser reads the file and draws it. When a browser asks for a PHP page, something happens first: a program on the server reads the file, runs every piece of PHP code inside it, and sends only the result to the browser. The browser never sees a single line of your PHP.
The name is an old joke that stuck. It began as "Personal Home Page"; the official expansion today is PHP: Hypertext Preprocessor, a name that refers to itself. The version you should be learning is PHP 8. This matters, because PHP 8 is a stricter, faster and considerably better-designed language than the PHP taught in many older textbooks and YouTube tutorials, and a lot of advice you will find online is quietly out of date.
Here is the practical difference between PHP and the languages you have probably already met. HTML, CSS and JavaScript run on the visitor's machine, so anyone can press Ctrl+U and read every line you wrote. PHP runs on your machine — the server — so your database password, your pricing rules and your query logic are never sent to anybody. That is the whole reason server-side languages exist, and it is why you cannot build a real login system with JavaScript alone: whatever the browser can read, the visitor can change.
- Runs on the server — the browser receives the finished output, never the source
- Talks to databases such as MySQL, MariaDB, PostgreSQL and SQLite
- Produces whatever the request needs: HTML pages, JSON for an API, CSV downloads, PDFs, resized images
- Handles form submissions, file uploads, sessions, logins and email
- Free and open source, and available on nearly every cheap shared-hosting plan — which is why so many college and client projects end up on it
- Runs WordPress, Drupal and Magento, and modern frameworks such as Laravel and Symfony are built on it
Request and Response: The Loop Everything Happens Inside
Every PHP page you will ever write lives inside one short cycle. A browser sends a request; the server runs your script; your script produces a response; the server sends it back; and then your script is thrown away. Understanding that last part early will save you weeks of confusion.
"Thrown away" is literal. Every variable, every object, every open database connection disappears the moment the response is sent. If a visitor fills in a form on one page and you want to greet them by name on the next page, PHP does not remember anything on its own — the second request starts with completely empty memory, as if the first one never happened. This is called being stateless, and it is why later lessons in this course spend so much time on sessions, cookies and databases. Those are the three ways of carrying information from one request to the next.
Compare that with a desktop program or a mobile app, which starts once and keeps its variables alive for hours. A PHP script typically lives for a few milliseconds. When someone tells you "PHP forgets everything", they are not criticising the language — they are describing how the web itself works.
- The visitor's browser requests
https://example.com/contact.php - The web server (Apache, Nginx, or PHP's own built-in server) sees the
.phpextension and hands the file to PHP - PHP runs the file top to bottom, executing code and collecting anything you echo
- PHP hands the finished text — usually HTML — back to the web server
- The web server sends it to the browser, which renders it like any other page
- PHP discards every variable in the script and waits for the next request
- This is also why "my variable is empty on the next page" is the single most common beginner question in PHP. It is not a bug. Nothing survives a request unless you deliberately store it in a session, a cookie, a database or a file.
Your First PHP Script
PHP code lives between the tags <?php and ?>. Anything outside those tags is sent to the browser untouched; anything inside is executed. The file must be saved with a .php extension, because that is how the web server decides to involve PHP at all.
Three details in the example below are worth naming. echo is the instruction that adds text to the response — it is not a function you "return" from, it simply writes. Every statement ends with a semicolon, and a forgotten semicolon is the cause of most of the syntax errors you will hit in your first week. Comments come in two forms: // for a single line and /* ... */ for a block, and PHP ignores both completely.
Notice also what the visitor sees. If you view the page source in the browser, there is no <?php, no echo, no date() — only the plain text those instructions produced. Your source code stays on the server. That is not a security feature you switched on; it is simply how PHP works.
<?php
// A single-line comment
/* A block comment,
which can run over several lines */
echo "Hello, World!";
$college = "City College";
echo "Welcome to " . $college; // the dot joins strings together
// Run this file from the terminal with: php hello.php
// Or serve the folder with: php -S localhost:8000 - Double-clicking a
.phpfile will never work. The browser opens it as a plain file (afile://address), so nothing runs PHP and you either see your raw code or a blank page. PHP pages must be requested through a server — XAMPP, or PHP's built-in server started withphp -S localhost:8000, and then opened athttp://localhost:8000/hello.php.
Mixing PHP Into HTML
PHP was designed to be embedded inside HTML, and you can open and close the tags as many times as you like in one file. This makes it very easy to build a page whose content changes — a result page that lists whatever rows came back from the database, a navigation bar that shows "Logout" only when someone is logged in.
Because printing a value inside HTML is so common, PHP gives you a shorthand: <?= $value ?> means exactly the same as <?php echo $value; ?>. It is always available in PHP 8 and is the normal way to write templates. For loops and conditions inside HTML, PHP also offers an alternative syntax that swaps the closing brace for endif;, endforeach; and so on. It exists because a stray } lost among fifty lines of HTML is genuinely hard to find, whereas endforeach; tells you what it closes.
One habit worth forming from your very first project: do the thinking at the top of the file, and the printing at the bottom. Fetch your data, run your checks, decide what to show — all before the first line of HTML. Then let the HTML part contain nothing but simple loops and value printing. Files where database queries are scattered between <div> tags become unmaintainable faster than you would believe, and "headers already sent" errors, which a later lesson explains, come almost entirely from this mistake.
<?php
// --- all the logic first ---
$student = "Ananya";
$subjects = ["Physics", "Chemistry", "Maths"];
$isLoggedIn = true;
?>
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Welcome, <?= $student ?></h1>
<p>Today is <?= date("d M Y") ?></p>
<ul>
<?php foreach ($subjects as $subject): ?>
<li><?= $subject ?></li>
<?php endforeach; ?>
</ul>
<?php if ($isLoggedIn): ?>
<a href="logout.php">Logout</a>
<?php else: ?>
<a href="login.php">Login</a>
<?php endif; ?>
</body>
</html> - In a file that is only PHP — a class file, a config file, a database helper — leave off the closing
?>entirely. It is not required, and any blank line or stray space after it gets sent to the browser as output, which breaks redirects and sessions in ways that are painful to debug.
The First Security Habit: Escape What You Print
It feels early to talk about security in lesson one, but this one habit is easier to learn now than to retrofit later. The moment you print something a visitor supplied — a name from a form, a search term from the URL — you are inserting text you did not write into your own HTML. If that text happens to contain HTML tags, the browser will obey them.
That is cross-site scripting, usually shortened to XSS. Someone visits ?name=<script>...</script>, your page prints it as-is, and now their JavaScript is running on your site, with access to your visitors' cookies. It is not a theoretical attack; it is one of the most common flaws found in student and small-business PHP sites.
The fix is a single function. htmlspecialchars() converts the characters that mean something in HTML — <, >, &, quotes — into their harmless display equivalents, so a script tag shows up on screen as text instead of running. The rule to memorise is short: escape at the moment you print, every single time. Do not try to clean data on the way in and trust it later; you will always miss a path.
<?php
// URL: greet.php?name=Ananya
$name = $_GET['name'] ?? 'Guest';
// DANGEROUS - prints whatever the visitor typed, tags and all
echo "<h1>Hello, $name</h1>";
// SAFE - tags are shown as text, never executed
echo "<h1>Hello, " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "</h1>";
// A short helper saves typing, and you will use it on every page
function e(?string $value): string {
return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
}
echo "<h1>Hello, " . e($name) . "</h1>"; $_GET['name'] ?? 'Guest'uses the null coalescing operator. It means "use this value if it exists and is not null, otherwise use the fallback". Without it, a visitor arriving without?name=in the URL triggers an "Undefined array key" warning.
How to Not Get Stuck in Week One
Almost every beginner loses hours to the same handful of problems, and all of them have short answers. The worst is the blank white page: you load your script and get nothing at all, not even an error. That means PHP hit a fatal error while error display was switched off, so the message went into a log file instead of onto your screen. On your own machine you always want to see errors, so turn them on while you learn.
The second is a habit rather than a fix: read the error message from the left. PHP tells you the file, the line number and what it expected. "Parse error: syntax error, unexpected token, expecting ';'" on line 42 usually means the semicolon is missing at the end of line 41, because PHP only notices something is wrong when it reaches the next line. Beginners often stare at the reported line and never look up one.
Finally, get comfortable with var_dump(). It prints a value along with its type and, for arrays, its full structure. When your condition behaves strangely, dumping the variable is nearly always faster than guessing. print_r() is a tidier alternative for arrays when you only want to see the contents.
- Blank page with no message — a fatal error with display off; switch errors on in your development setup
- Code shows as text in the browser — the file was opened directly instead of through a server, or the extension is not
.php - "Undefined variable" — a typo; PHP variable names are case-sensitive, so
$Nameand$nameare two different variables - "Undefined array key" — you read
$_POST['x']when the form did not send it; use??to supply a default - "Cannot modify header information — headers already sent" — something printed before your redirect or
session_start(); look for a space before<?php - Use
var_dump($x);to see a value and its type, andprint_r($arr);to read an array quickly
