Introduction to PHP: What It Is, How It Works, and Your First Script
There's a reason PHP is still running the backend of WordPress, Facebook's early codebase, Wikipedia, and millions of e-commerce stores. When the web needed a way to make pages dynamic — to show your name after you log in, to pull products from a database, to process a payment — PHP was the tool that made it possible, and it's been doing it reliably since 1994. Learning PHP isn't just learning a language; it's learning how the majority of the web actually thinks.
Before PHP existed, every webpage was just a static HTML file — like a printed flyer that said the same thing to everyone who read it. If you wanted to show a personalised dashboard, you had to manually write a different HTML file for every single user. That's obviously insane. PHP solved this by letting developers write logic inside their web pages — 'if this user is logged in, show THIS; if not, show THAT.' One template, infinite personalised outcomes. That's the core problem PHP was built to solve.
By the end of this article you'll understand exactly what PHP is and where it runs, you'll have written and executed your first real PHP script, you'll understand variables, echo, and basic data types, and you'll know the most common beginner mistakes so you can skip the hours of frustrated Googling that everyone else goes through.
What PHP Actually Is — and Where It Lives
PHP stands for 'PHP: Hypertext Preprocessor' — yes, the acronym contains itself, which is a programmer joke called a recursive acronym. Don't worry about that. What matters is what PHP does.
PHP is a server-side scripting language. 'Server-side' means the PHP code runs on the web server — a powerful computer somewhere in the world — not inside your visitor's browser. The browser never sees your PHP code. It only ever receives the final HTML output that PHP produces. This is completely different from JavaScript, which runs inside the browser itself.
Think of it like this: when you order a burger at a drive-through, you never see the kitchen. You just get the finished burger through the window. PHP is the kitchen. Your browser is the drive-through window. The HTML page is the burger.
PHP files have the extension .php. Inside them, you can write regular HTML, and whenever you need the server to do something dynamic — fetch data, run logic, personalise content — you drop into PHP code using special tags. The server processes those tags, replaces them with real output, and sends clean HTML to the browser. The browser is none the wiser.
<?php // Everything between <?php and ?> is processed by the PHP server engine. // The result replaces these tags before being sent to the browser. // php_uname() returns info about the server OS — proof this runs on the server, not the browser. $serverName = php_uname('n'); // date() formats the current server date/time — this changes every time the page loads. $todayDate = date('l, F j, Y'); // phpversion() returns which version of PHP the server is running. $phpVersion = phpversion(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My First PHP Page</title> </head> <body> <h1>Hello from the Server!</h1> <!-- We switch back into PHP to output dynamic values using echo --> <p>Today is: <?php echo $todayDate; ?></p> <p>This page was served by: <?php echo $serverName; ?></p> <p>Running PHP version: <?php echo $phpVersion; ?></p> </body> </html>
Today is: Tuesday, June 10, 2025
This page was served by: MyWebServer
Running PHP version: 8.2.12
Variables, Data Types, and echo — The Building Blocks You'll Use Every Day
In PHP, a variable is a named container that holds a value. Think of it like a labelled box — you put something in the box, give the box a name, and you can refer to that name anywhere in your code to get the value back out.
Every PHP variable starts with a dollar sign $. That's non-negotiable — no dollar sign, no variable. After the dollar sign comes the name you choose. Good variable names are descriptive: $customerName is infinitely better than $cn or $x.
PHP is 'loosely typed', which means you don't have to tell PHP what kind of data you're storing. You just store it, and PHP figures out the type automatically. This is a blessing for beginners and occasionally a curse for experienced developers — we'll cover the gotcha that comes with this in the mistakes section.
The most important PHP function you'll use daily is echo. It outputs content — text, numbers, HTML — directly into the page. You'll use it constantly. There's also print, which does almost the same thing, but echo is faster, more common, and can output multiple values at once. Always use echo.
<?php // --- STRINGS: text wrapped in quotes --- $customerFirstName = "Alice"; // Double quotes allow variable expansion inside them $welcomeMessage = 'Welcome back, '; // Single quotes are treated as literal text — no expansion // --- INTEGERS: whole numbers, no decimal point --- $itemsInCart = 3; $customerAge = 28; // --- FLOATS: numbers with decimal places --- $itemPrice = 19.99; $taxRate = 0.08; // 8% tax // --- BOOLEANS: true or false, nothing else --- $isLoggedIn = true; $hasProAccount = false; // --- NULL: deliberately empty, no value assigned --- $pendingOrder = null; // gettype() tells you what PHP thinks the variable's type is — great for debugging echo gettype($customerFirstName) . "\n"; // Outputs: string echo gettype($itemsInCart) . "\n"; // Outputs: integer echo gettype($itemPrice) . "\n"; // Outputs: double (PHP calls floats 'double') echo gettype($isLoggedIn) . "\n"; // Outputs: boolean echo gettype($pendingOrder) . "\n"; // Outputs: NULL // --- CONCATENATION: joining strings together using the dot (.) operator --- // This is PHP's way of gluing strings together — NOT the + sign like in JavaScript $fullGreeting = $welcomeMessage . $customerFirstName . "!"; echo $fullGreeting . "\n"; // Outputs: Welcome back, Alice! // --- ARITHMETIC: PHP handles maths naturally --- $orderTotal = $itemsInCart * $itemPrice; // 3 x 19.99 = 59.97 $taxAmount = $orderTotal * $taxRate; // 59.97 x 0.08 = 4.7976 $finalTotal = $orderTotal + $taxAmount; // 59.97 + 4.7976 = 64.7676 // number_format() rounds a float to 2 decimal places — essential for any money calculation $formattedTotal = number_format($finalTotal, 2); // "64.77" echo "Cart total for " . $customerFirstName . ": $" . $formattedTotal . "\n"; // Outputs: Cart total for Alice: $64.77 // --- BOOLEAN output quirk: var_dump() is better than echo for booleans --- // echo on a boolean gives you '1' for true and '' (nothing) for false — confusing! echo $isLoggedIn; // Outputs: 1 (not 'true' — a classic beginner confusion) echo "\n"; var_dump($isLoggedIn); // Outputs: bool(true) — much clearer for debugging ?>
integer
double
boolean
NULL
Welcome back, Alice!
Cart total for Alice: $64.77
1
bool(true)
PHP Tags, Comments, and How a PHP File is Actually Structured
Understanding the structure of a PHP file is the thing that separates beginners who 'write PHP' from beginners who actually understand what they're doing. Let's get this locked in clearly.
PHP code must live inside opening and closing tags: to start, ?> to end. Everything outside those tags is treated as raw HTML and sent to the browser exactly as written. Everything inside is processed by PHP. You can have multiple PHP blocks in a single file, switching in and out of PHP as many times as you need.
One important rule: if a file contains only PHP and no HTML at all (which is very common for backend logic files), you should use the opening tag but deliberately omit the closing ?> tag. This prevents a nasty bug caused by accidental whitespace after the closing tag that can corrupt HTTP headers.
Comments in PHP come in three flavours: // for a single-line comment, # also for single-line (less common), and / ... / for multi-line comments. Comments are stripped out by PHP and never sent to the browser — they're purely for developers reading the code.
<?php /* * Multi-line comment block. * Use this at the top of files or above complex functions * to explain the PURPOSE of the code, not just what it does. * * File: php_structure_explained.php * Purpose: Demonstrate PHP file structure and comment styles */ // Single-line comment: use for quick notes on a specific line $siteName = "TheCodeForge"; // You can also put comments at the END of a code line $articleYear = 2025; # This also works as a single-line comment, but // is far more common in modern PHP $authorName = "Alex"; ?> <!-- We are now OUTSIDE PHP — this is regular HTML the server passes straight through --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title><?php echo $siteName; ?> - Learn PHP</title> <!-- This is an HTML comment — completely different from a PHP comment. HTML comments ARE sent to the browser and visible in View Source. PHP comments are NOT sent — they're consumed by the server. Never put passwords or secrets in HTML comments! --> </head> <body> <?php // We've jumped BACK into PHP to do some logic $currentYear = date('Y'); // Gets the current 4-digit year from the server // A simple conditional — we'll cover these fully in the next article if ($currentYear === $articleYear) { $yearMessage = "This article is brand new!"; } else { $yearMessage = "Written in " . $articleYear . ", still accurate today."; } ?> <!-- Back to HTML, but we echo PHP variables inline using the short echo tag --> <h1>Welcome to <?php echo $siteName; ?></h1> <p>Written by <?php echo $authorName; ?> — <?php echo $yearMessage; ?></p> <p>Server year check: <?php echo $currentYear; ?></p> </body> </html> <?php /* * IMPORTANT: If this were a pure PHP file (no HTML), we would NOT include * a closing ?> tag at the end. This prevents 'headers already sent' errors * caused by invisible whitespace or newlines after the closing tag. * * Rule of thumb: * Mixed PHP + HTML file → include closing ?> * Pure PHP logic file → OMIT the closing ?> */ ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TheCodeForge - Learn PHP</title>
</head>
<body>
<h1>Welcome to TheCodeForge</h1>
<p>Written by Alex — This article is brand new!</p>
<p>Server year check: 2025</p>
</body>
</html>
Setting Up PHP Locally — Running Your First Real Script in Under 5 Minutes
You need a PHP environment to run PHP code. PHP is a server-side language, which means you can't just open a .php file in your browser like you can with HTML — the browser doesn't know how to process it. You need a PHP interpreter installed on your machine (or a server). Here are your two practical options.
Option 1 — PHP's built-in development server (Recommended for beginners). If you install PHP directly, you get a built-in web server perfect for local development. No Apache, no Nginx, no configuration nightmares. One command in your terminal and you're live.
Option 2 — XAMPP or Laragon (All-in-one stack). These tools install PHP, a web server (Apache), and a database (MySQL) in one click. Great if you want to build database-connected apps quickly. Laragon is the modern, faster alternative to XAMPP on Windows.
For this article, we'll use PHP's built-in server since it has zero setup complexity. Once PHP is installed (php.net/downloads), you literally just run one command.
<?php /* * This is the complete, runnable first PHP script. * * HOW TO RUN IT: * 1. Save this file as hello_world_complete.php * 2. Open your terminal in the same folder * 3. Run: php -S localhost:8000 * 4. Open your browser and go to: http://localhost:8000/hello_world_complete.php * 5. You should see the output below. * * Alternatively, run from terminal WITHOUT a browser: * php hello_world_complete.php */ // Grab the current hour of the day from the server (0 = midnight, 23 = 11pm) $currentHour = (int) date('G'); // date('G') returns 0-23, (int) converts string to integer // Decide what greeting to show based on the time of day if ($currentHour >= 5 && $currentHour < 12) { $timeGreeting = "Good morning"; $emoji = "☀️"; } elseif ($currentHour >= 12 && $currentHour < 17) { $timeGreeting = "Good afternoon"; $emoji = "⛅"; } elseif ($currentHour >= 17 && $currentHour < 21) { $timeGreeting = "Good evening"; $emoji = "🌆"; } else { $timeGreeting = "Working late, are we"; $emoji = "🌙"; } // The visitor's name would normally come from a login system or URL parameter // For now, we hardcode it — we'll replace this with real user data in later articles $visitorName = "Future PHP Developer"; // PHP_EOL is a constant that outputs the correct line ending for the current OS // On Windows it's \r\n, on Mac/Linux it's \n — using PHP_EOL makes your code portable echo $timeGreeting . ", " . $visitorName . "! " . $emoji . PHP_EOL; echo "------------------------------------------" . PHP_EOL; echo "The server time is: " . date('H:i:s') . PHP_EOL; echo "PHP version running: " . phpversion() . PHP_EOL; echo "------------------------------------------" . PHP_EOL; // strlen() counts the number of characters in a string — useful all the time $nameLength = strlen($visitorName); echo "Your name has " . $nameLength . " characters in it." . PHP_EOL; // strtoupper() transforms a string to ALL CAPS echo "Shouting your name: " . strtoupper($visitorName) . PHP_EOL; // str_word_count() counts how many words are in a string $wordCount = str_word_count($visitorName); echo "Your name contains " . $wordCount . " words." . PHP_EOL;
------------------------------------------
The server time is: 14:23:47
PHP version running: 8.2.12
------------------------------------------
Your name has 22 characters in it.
Shouting your name: FUTURE PHP DEVELOPER
Your name contains 3 words.
| Feature / Aspect | PHP (Server-Side) | JavaScript (Client-Side) |
|---|---|---|
| Where it runs | On the web server before the page is sent | Inside the user's browser after the page loads |
| User can see the code? | No — only the HTML output is sent | Yes — fully visible in browser DevTools |
| Accesses databases? | Yes — directly and securely | Not directly — needs a server API in between |
| Reads/writes files on server? | Yes — full filesystem access | No — sandboxed in the browser |
| Changes page without reload? | No — requires a new HTTP request | Yes — can update the DOM live |
| File extension | .php | .js |
| Needs a server to run? | Yes — always | No — runs in any modern browser |
| Best used for | Login systems, databases, APIs, email | Animations, form validation, dynamic UI |
| Can they work together? | Yes — and they do on almost every modern site | Yes — PHP generates HTML, JS enhances it |
🎯 Key Takeaways
- PHP runs on the server, not the browser — the browser only ever receives the final HTML output. Your PHP code is never exposed to the end user.
- Every PHP variable starts with a dollar sign ($). Forgetting it is the single most common beginner syntax error — and the error message isn't always obvious about why.
- Use the dot (.) operator to join strings in PHP, not the plus (+) sign. Using + on strings gives you arithmetic results, not concatenation.
- For files that contain only PHP (no HTML), omit the closing ?> tag to prevent 'headers already sent' errors caused by invisible trailing whitespace.
⚠ Common Mistakes to Avoid
- ✕Mistake 1: Forgetting the dollar sign on a variable — Writing 'customerName = "Alice"' instead of '$customerName = "Alice"' — PHP throws a parse error: 'unexpected token' or 'undefined constant'. The fix is simple: every single variable in PHP starts with $. No exceptions. If your code isn't working and you're staring at it confused, scan every variable name and make sure the $ is there.
- ✕Mistake 2: Using + to concatenate strings instead of the dot operator — Writing '$fullName = $firstName + $lastName' produces 0 or unexpected numeric output because + is the arithmetic addition operator in PHP, not string joining. JavaScript uses + for strings, but PHP uses a dot (.) — '$fullName = $firstName . " " . $lastName'. This trips up anyone coming from JavaScript or Python.
- ✕Mistake 3: Opening a .php file directly in the browser instead of running it through a server — You either see raw PHP code printed on screen, or a completely blank page, or just the HTML parts without any dynamic output. The fix: always access PHP files through a server URL (like http://localhost:8000/file.php), never by double-clicking the file and opening it as file:///path/to/file.php. PHP must pass through a PHP interpreter — the browser has none.
Interview Questions on This Topic
- QWhat does 'server-side' mean in the context of PHP, and why does it matter for security?
- QWhat is the difference between single quotes and double quotes in PHP strings — and when would you choose one over the other?
- QIf PHP is loosely typed, why might that cause bugs, and what PHP function can you use to check a variable's type at runtime?
Frequently Asked Questions
Is PHP still worth learning in 2025?
Absolutely. PHP powers roughly 77% of all websites with a known server-side language, including WordPress (which runs 43% of the entire internet), Wikipedia, and countless e-commerce platforms. The ecosystem is mature, the job market is steady, and PHP 8.x has modern features that make it genuinely enjoyable to write. It's not trendy, but it pays the bills reliably.
What's the difference between PHP and HTML?
HTML is a markup language that describes the structure of a page — it's static and looks the same for every visitor. PHP is a programming language that runs on the server and generates HTML dynamically. Think of HTML as a printed form and PHP as the person filling it out differently for each visitor based on who they are and what they requested.
Do I need to know HTML before learning PHP?
A basic understanding of HTML helps a lot because PHP is most commonly used to generate HTML pages. You don't need to be an HTML expert — knowing tags like
,
, , and
Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful — not just SEO filler.