Thuta Learning
PHP
BasicProgrammingBeginner

PHP HOME

PHPLesson 115 min

What you'll walk away with

  • Say in a few words where PHP code runs and what the browser actually receives
  • Trace one request through the browser, the web server, the PHP engine and the response
  • Run a PHP script from the command line with `php welcome.php` and read its output
  • Know the five chapters (Basic, Intermediate, Advanced, Projects, Exercises) and the order to study them

Explain it simply

PHP in plain words

PHP is a programming language that runs on a computer you control, called the server, instead of inside the visitor's browser. When someone opens a page, the server runs your PHP file, which decides what that page should say, and sends back only the finished result.

Think of a restaurant kitchen. The customer (the browser) places an order and receives a finished plate, but never sees the recipe (your PHP source code). Because the cooking happens on the server, PHP can look things up in a database or check a password in a place the visitor can never see.

Problem → Why → Solution

The problem: a plain HTML page is the same for everyone

Imagine a restaurant website with 500 menu items. With plain HTML you write one file per item by hand. Changing a single price means opening the right file and editing it, and greeting a returning customer by name is impossible, because the page shows exactly the same thing to whoever visits.

An HTML file is like a printed photograph. It knows nothing about who is asking, what time it is or what the data currently says. What you need is code that wakes up for every request, finds the data and writes fresh HTML on the spot.

product-17.html
<!-- one hand-written file per menu item: product-1.html ... product-500.html -->
<h1>Tea leaf salad</h1>
<p>Price: 3500 MMK</p>
<p>Welcome back, Aye Aye!</p>
<!-- the same greeting for every visitor, and 500 files to edit when prices change -->

Why this hurts

Writing every page by hand multiplies the places you must edit and the chances of a typo. With PHP, one template can be filled with data and the HTML produced on every request, so changing a price in one place updates all 500 pages.

Core concept: PHP builds the page on the server for every request

When you open a web page, the browser and a server talk over HTTP. The browser sends a request (a letter that says which URL and which method) and the server sends back a response. The server is web server software such as Apache or Nginx, and PHP also ships with a small development server. When a request points at a `.php` file, the web server hands that file to the PHP engine.

The browser sends a request

A request such as `GET /shop.php` carries the URL, the method and some headers.

The PHP engine runs the file top to bottom

It carries out each statement in order and may query a database or do calculations along the way.

Whatever PHP prints becomes the response body

The text produced with `echo`, usually HTML, is sent back by the server together with a status code and headers.

The browser sees only the result

The PHP source is never sent, which is why View Source in a browser shows only the HTML.

text
One request, from click to page
-------------------------------
  Browser            Web server + PHP                 Database / files
  -------            ----------------                 ----------------
    | GET /shop.php        |                                  |
    |--------------------->| run shop.php top to bottom       |
    |                      |--------------------------------->| query
    |                      |<---------------------------------| rows
    |                      | build the HTML with echo         |
    |<---------------------| 200 OK + HTML (no PHP code)      |
    | render the page      |                                  |

PHP also works without any web server. Typing `php script.php` in a terminal runs the same language and simply prints the output in the terminal instead of sending it to a browser. The first part of this course uses that route, so you can study the language itself before configuring a server. Web-specific topics such as forms and sessions join in later, once a browser is involved.

One more distinction will save you confusion later. 'PHP' names the language you write, the engine that executes it and the SAPI (server API) that connects the engine to the outside world. The same engine can be started by a terminal (the `cli` SAPI), by PHP-FPM behind Nginx, or by Apache, and each start-up may read different settings from its own php.ini. The next lesson looks at these pieces one by one.

A mental model: kitchen and plate
  1. Browser sends a request
  2. Server hands the .php file to PHP
  3. PHP runs and prints the page
  4. Browser receives only the output

PHP code stays on the server and only its output travels to the browser. That is why a browser button cannot call a PHP function directly; it has to send a new request.

General pattern: a PHP script

php
<?php
declare(strict_types=1);

function name(Type $param): ReturnType
{
    return $result;
}

echo name($argument), PHP_EOL;

A script starts with `<?php`. `declare(strict_types=1);` makes type checking strict. A function declares parameter types and a return type, and `echo` sends the result to the output. `PHP_EOL` adds a line break at the end of the line.

Your first PHP script

Save the script below as `welcome.php`. Open a terminal in that folder and type `php welcome.php` to run it. Setup is covered properly in lesson 3; for now just read the code and predict what it prints. The last line reports how the script is being run.

welcome.php
<?php
declare(strict_types=1);

function welcome(string $name, int $lessonsLeft): string
{
    return "Hi {$name}, {$lessonsLeft} lessons to go!";
}

$total = 36;
$done = 1;

echo welcome("Aye Aye", $total - $done), PHP_EOL;
echo "This script ran under the ", PHP_SAPI, " SAPI.", PHP_EOL;

Code breakdown

  1. The opening tag<?php

    PHP treats only the part between `<?php` and `?>` as code. With the tag at the very top of the file, everything below it is PHP.

  2. Strict typesdeclare(strict_types=1);

    Because of this line, passing a string like `"10"` where an `int` is expected is no longer converted silently and raises a TypeError instead. It must be the first statement in the file.

  3. Typed parameters and return typefunction welcome(string $name, int $lessonsLeft): string

    One line makes three promises: `$name` is a string, `$lessonsLeft` is an int and the function returns a string.

  4. A string with variables insidereturn "Hi {$name}, {$lessonsLeft} lessons to go!";

    Writing `{$name}` inside a double-quoted string inserts the variable's value. The curly braces make it clear where the variable name ends.

  5. Call and printecho welcome("Aye Aye", $total - $done), PHP_EOL;

    `$total - $done` is an int, so it fits the second parameter. `echo` accepts several values separated by commas, and `PHP_EOL` supplies the line break.

  6. A built-in constantecho "This script ran under the ", PHP_SAPI, " SAPI.", PHP_EOL;

    `PHP_SAPI` is a built-in constant that says how PHP was started. From a terminal it is `cli`; under a web server it holds a different value.

You should see
Hi Aye Aye, 35 lessons to go!
This script ran under the cli SAPI.
From URL to page
  1. Browser requests /welcome.php
  2. Web server finds the file
  3. PHP engine runs it top to bottom
  4. The output becomes the HTTP response
  5. Browser renders the HTML

The file ends in .php

PHP runs it and sends the output

The file ends in .html

Sent as it is, no PHP is executed

How this course is organized

The course has 36 lessons in five chapters, and each chapter builds on the one before it. Follow them in order: the form lessons in Intermediate assume you can already write functions and arrays, and the database lessons assume you know forms and the security basics.

ChapterLessonsWhat you learn
Basic1-10Intro, setup, syntax, variables, echo and print, strings, numbers, arrays, operators
Intermediate11-19if/else, switch, loops, functions, strict types, superglobals, GET and POST, forms, validation
Advanced20-32Date and time, include, namespaces and Composer, sessions, security, classes, exceptions, MySQLi, PDO
Projects33-34A contact form project, then a summary with next steps
Exercises35-36Two practice sets that revisit the earlier chapters

Every lesson follows the same order: a plain explanation, a problem, the core concept, a general pattern, a worked example explained line by line, common mistakes, a mini challenge and three quiz questions. Run every example, change one value, and predict the output before you press Enter.

Two ways to run the examples

The fastest way is to run a script straight from the terminal. For lessons that need a browser, such as forms and sessions, you can use the development server that comes with PHP. It serves the current folder at `localhost:8000` and is meant for learning only, never for a website real people use.

bash
php welcome.php          # run one script and print its output in the terminal
php -S localhost:8000    # serve this folder to a browser (development only)
php -l welcome.php       # check the syntax without running the script

In real projects

PHP in real projects

PHP powers a very large part of the public web. Content management systems such as WordPress and Drupal are written in it, and frameworks such as Laravel and Symfony give teams a structured way to build shops, dashboards and APIs. Learning PHP also means learning the language of many existing codebases that companies need people to maintain and extend.

Modern PHP projects look different from the old one-file scripts. They use Composer to install libraries, PHPUnit for tests and tools such as PHPStan or Psalm to find type mistakes before a release, and they run PHP behind Nginx or Apache, usually through PHP-FPM. Recent PHP 8.x releases have type declarations, enums, attributes and match expressions, which is why this course teaches `declare(strict_types=1)` from the very first example.

Common mistakes

Common beginner mistakes

1. Opening the file instead of requesting it

Double-clicking `index.php`, or typing a path such as `C:/xampp/htdocs/index.php` into the address bar, makes the browser read the file from disk. No server is involved, so PHP never runs and you see raw source code or a download prompt. Request the page through a server, for example `http://localhost:8000/index.php`, or run it with `php index.php` in a terminal.

2. Expecting PHP to run inside the browser

A PHP script has finished before the page reaches the visitor. A button's `onclick` cannot call a PHP function, and View Source will not show your PHP, because only the output was sent. To react to a click you send a new request with a link, a form or JavaScript's `fetch`, and PHP runs again on the server.

3. Reading without running

PHP's warnings and type errors only start to make sense once you have seen them yourself. Run each example, then break it on purpose: remove a semicolon, pass a string where an int is expected, and read the message that comes back.

Best practices

Good habits from day one

  • Keep one folder per lesson or project so file paths and the run command stay simple.
  • Start every new script with `<?php` and `declare(strict_types=1);` so types are checked from day one.
  • Use `php -l file.php` to check the syntax without running the script, and do it after every save.

Mini challenge

Mini challenge: a course progress line

Write a typed function `progressLine` that takes the number of finished lessons and the total, and returns a string like `6 of 36 lessons done (17%)`.

  • Give both parameters the `int` type and the function a `string` return type
  • Round the percentage to a whole number with `round()`
  • When `$total` is 0, show `0%` (never divide by zero)
  • Print one line for 6 of 36 and one line for 0 of 0
progress.php
<?php
declare(strict_types=1);

// TODO: add int types to both parameters and a string return type
function progressLine($done, $total)
{
    // TODO: percent = done / total * 100, rounded (use 0 when total is 0)
    // TODO: return "<done> of <total> lessons done (<percent>%)"
}

// TODO: print the line for 6 of 36 and for 0 of 0

Expected: Prints `6 of 36 lessons done (17%)` and `0 of 0 lessons done (0%)`, one per line.

Show hint

Check `$total === 0` first and pick 0 with a ternary (`? :`). `round()` returns a float, so cast it with `(int)` to print `17` instead of `17.0`.

Show solution
progress.php
<?php
declare(strict_types=1);

function progressLine(int $done, int $total): string
{
    $percent = $total === 0 ? 0 : (int) round($done / $total * 100);
    return "{$done} of {$total} lessons done ({$percent}%)";
}

echo progressLine(6, 36), PHP_EOL;
echo progressLine(0, 0), PHP_EOL;

Quick quiz 1 / 3

A browser opens `http://localhost:8000/page.php`. What does it receive?

Quick quiz 2 / 3

Which command runs a PHP file in a terminal without any web server?

Quick quiz 3 / 3

With `function welcome(string $name, int $lessonsLeft): string` and `declare(strict_types=1);`, which call does PHP reject with a TypeError?

What to remember

  • PHP runs on the server, and only its output (usually HTML) reaches the browser
  • For each request the web server hands the `.php` file to the PHP engine and whatever it prints becomes the response
  • `php script.php` runs a script from the terminal with no web server at all
  • Work through the 36 lessons in the order Basic, Intermediate, Advanced, Projects, Exercises

Migrating to PHP 8.5 — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

PHP HOME | Thuta Learning