PHP Home
PHP is a server-side scripting language used to build dynamic websites, web applications, APIs, and command-line tools. A PHP script runs on the server, produces output (usually HTML), and sends only that output to the browser. The best way to understand PHP is to run it, so this lesson starts with working code.
Your First PHP Script
Example
<?php
echo "Hello, World!";
Output
Hello, World!
How the Example Works
| Part | Meaning |
|---|---|
<?php | The opening tag. It tells the PHP engine: "start interpreting everything after this as PHP code." Without it, PHP treats the text as plain output and prints it as-is. |
echo | A language construct that sends output. In a web page, that output becomes part of the HTML response sent to the browser. |
"Hello, World!" | A string — a sequence of characters wrapped in quotes. |
; | The semicolon ends the statement. PHP uses it to know where one instruction stops and the next begins. |
Notice that there is no closing ?> tag. When a file contains only PHP code, the closing tag is intentionally left out. This prevents accidental whitespace after ?> from being sent to the browser, which can break features such as redirects and cookies. The reason is explained in detail in the PHP Tags lesson.
Running the Script
- Save the code in a file named
hello.php. - Open a terminal in the same folder.
- Run:
php hello.phpThe terminal prints
Hello, World!. To view it in a browser instead, start PHP's built-in development server in the same folder:php -S localhost:8000Then open
http://localhost:8000/hello.php. Installation and the development server are covered in the PHP Install and PHP Built-in Web Server lessons.
PHP Inside an HTML Page
PHP was designed to be mixed with HTML. You can write a normal HTML document and insert PHP only where something must change dynamically.
Example
<!DOCTYPE html> <html> <head> <title>My First PHP Page</title> </head> <body> <h1>Welcome</h1> <p>Today is <?php echo date('l, d F Y'); ?>.</p> </body> </html>Output (HTML received by the browser)
<!DOCTYPE html> <html> <head> <title>My First PHP Page</title> </head> <body> <h1>Welcome</h1> <p>Today is Thursday, 08 October 2026.</p> </body> </html>How the Example Works
- Everything outside
<?php ... ?>is sent to the browser unchanged. - Everything inside the tags is executed on the server.
date('l, d F Y')returns the current date formatted with these characters:l— full day name (Thursday)d— day of the month with a leading zero (08)F— full month name (October)Y— four-digit year (2026)
- The result replaces the PHP block, so the browser only receives the finished sentence. If you open the page in a browser and choose View Page Source, you will not find
<?phpordate(...)anywhere. The browser never sees PHP code — only the result of running it. This is the core idea behind server-side programming.Note:
date()uses the server's configured timezone. If the date or time looks wrong, the timezone has not been set for your location. Timezones are covered in the Timezones lesson.
A Slightly Larger Example
The following script changes its greeting depending on the time of day. It uses variables, a condition, and string output — three concepts you will study in depth later.
Example
<?php $name = "Asha"; $hour = (int) date('G'); if ($hour < 12) { $greeting = "Good morning"; } elseif ($hour < 18) { $greeting = "Good afternoon"; } else { $greeting = "Good evening"; } echo "$greeting, $name!";Output (at 3 PM)
Good afternoon, Asha!Step-by-Step Explanation
$name = "Asha";creates a variable. In PHP, every variable name starts with$. The variable stores the string"Asha".date('G')returns the current hour in 24-hour format without a leading zero, such as"15". It returns a string.(int)converts that string into an integer. Comparing numbers with numbers is clearer and avoids surprises; type conversion is covered in PHP Casting and PHP Type Juggling.- The
if / elseif / elseblock checks the hour and stores a matching greeting in$greeting. Only the first condition that is true runs. echo "$greeting, $name!";prints the result. Because the string uses double quotes, PHP replaces$greetingand$namewith their values. With single quotes, the variable names would be printed literally. This behavior is explained in String Interpolation. This small script shows the typical shape of PHP code: collect data, make decisions, and produce output.
What Happens When You Request a PHP Page
Understanding this flow early prevents many beginner mistakes.
Browser Web Server PHP Engine | | | |-- GET /hello.php --------->| | | |-- "this is a .php file" -->| | | |-- runs the code | |<-- generated HTML ---------| |<-- HTML response ----------| |- The browser requests a URL such as
/hello.php. - The web server sees the
.phpextension and passes the file to the PHP engine instead of sending the file directly. - PHP executes the script from top to bottom.
- Whatever the script outputs becomes the HTTP response body.
- The browser receives plain HTML (or JSON, an image, a file download — whatever the script produced). Because the code runs on the server, PHP can safely work with things the browser must never access directly: database passwords, private files, payment API keys, and other users' data.
How Examples Are Presented in This Tutorial
Most lessons follow the same pattern:
- Example — a complete code block you can copy into a
.phpfile and run. - Output — what the script produces. For web pages, this is the HTML the browser receives or the visible result.
- Explanation — what each important part does and why it was written that way. When an example depends on a specific PHP version, the version is stated directly next to it, for example "PHP 8.1+". Running such code on an older version produces a syntax or fatal error. To experiment, change one thing at a time — a value, a condition, a function argument — and run the script again. Observing what changes, and what breaks, is one of the fastest ways to understand how PHP behaves.
Reading the Official PHP Manual
Every lesson in this tutorial links to the related page in the official PHP manual at
https://www.php.net/manual/en/. Learning to read the manual is a practical skill you will use throughout your career, so it is worth understanding its format now. Each function page starts with a signature. Here is the signature forstr_replace():str_replace( array|string $search, array|string $replace, string|array $subject, int &$count = null ): string|arrayHow to read it: | Part | Meaning | | --- | --- | |
str_replace| The function name. | |array0string $search| A parameter named$searchthat accepts an array or a string. The1means "either type" (a union type). | |int &$count| The&means this parameter is passed by reference: the function writes a value back into the variable you pass. | |= null| A default value. Parameters with defaults are optional. | |: string2array| The return type. This function returns a string or an array, depending on what you passed in. | A typical manual page then contains these sections: - Description — what the function does.
- Parameters — the meaning of each argument.
- Return Values — what you get back, including what is returned on failure (often
false). - Errors/Exceptions — what can go wrong.
- Changelog — which PHP versions changed the behavior. Check this when code works on one server but not another.
- Examples — official usage examples.
- See Also — related functions.
Note: Manual pages also contain user-contributed notes at the bottom. Some are useful, but many are old and describe behavior from outdated PHP versions. Treat them as hints, not as authoritative documentation.
PHP Versions
PHP releases a new minor version every year, usually in November. Each version receives two years of active support (bug and security fixes) followed by two years of security-only fixes. After that, it reaches end of life and receives no fixes at all. Supported branches as of October 2026: | Version | Released | Active Support Until | Security Support Until | | --- | --- | --- | --- | | PHP 8.2 | 8 Dec 2022 | Ended | 31 Dec 2026 | | PHP 8.3 | 23 Nov 2023 | Ended | 31 Dec 2027 | | PHP 8.4 | 21 Nov 2024 | 31 Dec 2026 | 31 Dec 2028 | | PHP 8.5 | 20 Nov 2025 | 31 Dec 2027 | 31 Dec 2029 | This tutorial uses modern PHP 8 syntax. Examples work on PHP 8.2 and newer unless a lesson states otherwise. Features introduced in later versions (such as property hooks in 8.4 or the pipe operator in 8.5) are clearly labeled. Check your installed version with:
php -vWarning: Do not start new projects on an end-of-life version (PHP 8.1 and older). These versions no longer receive security fixes, so any newly discovered vulnerability stays open permanently. The current support table is always available at
https://www.php.net/supported-versions.php.
Before You Start
You will learn faster if you are already comfortable with:
- HTML — PHP usually generates HTML, so you should recognize tags, forms, and links.
- Basic CSS — helpful for styling the pages you build, but not required to learn PHP itself.
- Using a terminal — running commands such as
php -vandphp -S. No previous programming experience is required. Programming concepts such as variables, conditions, loops, and functions are explained from the beginning.
Common Mistakes When Starting Out
Opening a
.phpFile Directly in the BrowserWhat happens: You double-click
hello.php, and the browser shows the raw code or downloads the file. The address bar shows something likefile:///C:/projects/hello.php. Why: The browser cannot execute PHP. Only a server that passes the file to the PHP engine can run it. Fix: Run the file through a server, for example withphp -S localhost:8000, and openhttp://localhost:8000/hello.php.Saving the File With the Wrong Extension
What happens: The server sends your code as plain text. Why: On Windows, file extensions are often hidden, so a file you named
hello.phpmay actually behello.php.txt. Fix: Enable "File name extensions" in Windows File Explorer (View menu) and confirm the file ends in.php.Forgetting the Semicolon
<?php echo "Hello" echo "World";PHP stops with a parse error similar to:
PHP Parse error: syntax error, unexpected token "echo", expecting "," or ";" in /path/hello.php on line 3Why: Without the semicolon, PHP thinks the first statement continues onto the next line and finds an unexpected
echo. Fix: Add;at the end of line 2. Notice that the error points to line 3 — the line where PHP noticed the problem. Parse errors often point to the line after the real mistake, so always check the previous line too.Seeing a Blank Page Instead of an Error
What happens: The script fails, but the browser shows an empty page. Why: Error display is turned off in the PHP configuration, which is the correct setting for production servers but makes learning difficult. Fix: On your development machine, set
display_errors = Onanderror_reporting = E_ALLinphp.ini. The PHP Install lesson shows exactly where to change this.
Tutorial Sections
Section Focus PHP Tutorial Syntax, variables, data types, strings, numbers, operators, conditions, loops PHP Functions Defining and calling functions, arguments, return values, closures, arrow functions PHP Arrays Indexed, associative, and multidimensional arrays, sorting, searching, transforming PHP Superglobals $_GET,$_POST,$_SERVER,$_SESSION, and other request dataPHP RegEx Pattern matching with the PCRE functions PHP Forms Handling, validating, sanitizing, and escaping form data PHP Advanced Dates, includes, files, uploads, cookies, sessions, JSON, exceptions, HTTP, cURL PHP OOP Classes, objects, inheritance, interfaces, traits, enums, namespaces, autoloading Modern PHP (8.x) Strict types, union types, attributes, fibers, readonly classes, property hooks MySQL Database MySQLi and PDO, prepared statements, CRUD, joins, pagination, transactions PHP XML SimpleXML, DOM, XMLReader, XMLWriter PHP - AJAX Communicating with PHP from JavaScript without page reloads PHP Security Password hashing, SQL injection, XSS, CSRF, sessions, file uploads, encryption PHP Tools & Deployment php.ini, CLI, Composer, PSR-4, extensions, debugging, OPcache, PHP-FPMPHP Projects Complete applications built from the concepts in earlier sections Official reference: https://www.php.net/manual/en/index.php