PHP Intro

La Lakshmi Priya Updated 17 Oct 2026
11 min read ·Lesson 13 of 22

What Is PHP?

In simple terms: PHP is a programming language that runs on a web server and builds web pages before they are sent to the visitor's browser.

Technically: PHP is an open-source, general-purpose scripting language that is especially suited to web development. Its code is executed on the server by the PHP engine (the Zend Engine), and the result — usually HTML — is returned to the client as an HTTP response.

The name PHP is a recursive acronym for PHP: Hypertext Preprocessor. The word preprocessor describes the original idea well: PHP processes a page before the browser receives it. PHP was created by Rasmus Lerdorf in 1994 as a set of tools for his personal home page, and it has grown into a full programming language maintained by a large open-source community.

Key characteristics:

  • Server-side — code runs on the server, never in the visitor's browser.
  • Interpreted — you do not compile PHP manually. The engine compiles the source into internal instructions each time it runs (or reuses a cached version).
  • Embeddable in HTML — PHP code can be placed directly inside HTML documents.
  • Dynamically typed with optional strict typing — variables do not need a declared type, but modern PHP lets you declare types for function parameters, return values, and class properties.
  • Cross-platform — runs on Linux, Windows, and macOS, with Apache, Nginx, and other web servers.

What Is a PHP File?

A PHP file is a text file with the .php extension. It can contain:

  • PHP code
  • HTML
  • CSS
  • JavaScript
  • Plain text

When the server runs a PHP file, only the PHP sections are executed. Everything else is passed through unchanged. The final output sent to the browser contains no PHP code.

Example

<!DOCTYPE html>
<html>
<body>
    <h1>Product List</h1>
    <?php
    $products = ["Keyboard", "Mouse", "Monitor"];

    foreach ($products as $product) {
        echo "<p>$product</p>";
    }
    ?>
</body>
</html>

Output (HTML received by the browser)

<!DOCTYPE html>
<html>
<body>
    <h1>Product List</h1>
    <p>Keyboard</p><p>Mouse</p><p>Monitor</p></body>
</html>

How the Example Works

  • $products is an array — a single variable holding several values.
  • foreach repeats the code inside its braces once for every item in the array. On each repetition, the current item is stored in $product.
  • echo outputs a <p> element for each product.

In a real application, the product names would come from a database instead of being written in the code. The HTML structure stays the same; only the data changes. That is what "dynamic page" means: one PHP file can produce different HTML for different requests, users, or data.

Notice the output formatting: the <p> elements appear on a single line because echo outputs exactly what you give it — no automatic line breaks. This does not affect how the browser renders the page, but it explains why generated HTML often looks compressed in View Source.


How PHP Works: The Request–Response Cycle

Every time someone visits a PHP page, the following happens:

1. Browser  ──── HTTP request: GET /products.php?id=7 ────▶  Web server (Nginx / Apache)
2. Web server sees ".php" and hands the request to PHP (usually PHP-FPM)
3. PHP engine:
      source code → tokens → syntax tree → opcodes → execution
4. The script runs: reads input, queries the database, builds output
5. Web server  ◀──── generated output ──── PHP
6. Browser  ◀──── HTTP response: HTML ──── Web server
7. PHP frees all memory used by the request

What Each Step Means

Step 2 — Handing the request to PHP. The web server does not understand PHP. It is configured to forward .php requests to the PHP engine. On modern servers, that engine usually runs as PHP-FPM (FastCGI Process Manager), a pool of worker processes waiting for requests. This setup is covered in the PHP-FPM lesson.

Step 3 — Compiling to opcodes. PHP reads the source code and converts it into opcodes, low-level instructions the Zend Engine executes. Doing this on every request would be wasteful, so production servers enable OPcache, which stores the compiled opcodes in shared memory. On later requests, PHP skips compilation and executes the cached opcodes directly. This is one of the most important performance settings in PHP and has its own lesson.

Step 4 — Running the script. The script can read the URL, form data, cookies, and headers; talk to databases and external APIs; and decide what to output.

Step 7 — Cleaning up. When the response is complete, PHP discards the variables, objects, and memory the script used. The next request starts with a clean state.


Why Every Request Starts Fresh

Step 7 has an important consequence that surprises many beginners.

Example

<?php
$visits = 0;
$visits++;

echo "This page has been visited $visits time(s).";

Output (every time you refresh)

This page has been visited 1 time(s).

Why the Counter Never Increases

Each request runs the script from the beginning. $visits is created, set to 0, increased to 1, printed — and then destroyed when the request ends. The next request has no memory of the previous one.

This design is called a shared-nothing architecture: requests do not share memory with each other.

To remember data between requests, you must store it somewhere that outlives the request:

StorageTypical UseLesson
SessionsData for one user across pages (login state, shopping cart)PHP Sessions
CookiesSmall values stored in the user's browserPHP Cookies
DatabasePermanent application data (users, orders, posts)MySQL Database
FilesLogs, uploads, exportsPHP File Handling
Cache servers (Redis, Memcached)Fast temporary data shared by all requests—

Why PHP Works This Way

The shared-nothing model has real advantages:

  • Isolation — an error or memory leak in one request cannot corrupt another request.
  • Simplicity — you rarely need to worry about two requests changing the same variable at the same time.
  • Easy scaling — because no request depends on memory from another, you can run the same application on several servers behind a load balancer.

The trade-off is that the application has to start up on every request. OPcache, preloading, and efficient code keep this cost small. Some newer runtimes (such as FrankenPHP worker mode, RoadRunner, or Swoole) keep the application in memory between requests for extra speed, but they change these rules and require more careful code. The traditional model is the right starting point for learning.


What Can PHP Do?

PHP is mostly used for web development, but it is not limited to it.

  • Generate dynamic pages — show different content for different users, dates, or data.
  • Handle forms — receive, validate, and process data submitted from HTML forms.
  • Manage users — registrations, logins, password hashing, sessions, and permissions.
  • Work with databases — create, read, update, and delete data in MySQL, MariaDB, PostgreSQL, SQLite, and others through PDO or MySQLi.
  • Build APIs — return JSON to mobile apps and JavaScript front ends.
  • Call other APIs — communicate with payment gateways, SMS services, and AI APIs using cURL or HTTP clients.
  • Work with files — read and write files, process uploads, generate CSV exports.
  • Send email — notifications, password resets, contact form messages.
  • Process images — resize, crop, and watermark images with extensions such as GD or Imagick.
  • Run command-line scripts — scheduled jobs (cron), data imports, queue workers, maintenance tasks.
  • Encrypt data — using the built-in Sodium extension.

Well-known software built with PHP includes WordPress, Drupal, Magento, MediaWiki (Wikipedia's software), and applications built with the Laravel and Symfony frameworks.


PHP vs Client-Side JavaScript

Beginners often confuse server-side and client-side code. Both can make a page "dynamic", but they work in completely different places.

AspectPHP (server-side)JavaScript (client-side, in the browser)
Where it runsOn the web serverIn the visitor's browser
When it runsBefore the page is sentAfter the page arrives
Can the visitor see the code?No — only the outputYes — anyone can read it
Can it access the database directly?YesNo (it must call a server API)
Can it safely hold secrets (API keys, DB passwords)?YesNo
Can it change the page without reloading?No — it needs a new requestYes — it manipulates the DOM
Typical useBusiness logic, data storage, authenticationInteractivity, animations, instant UI updates

They are usually used together: PHP produces the page and provides data, while JavaScript makes the page interactive. The PHP - AJAX section shows how JavaScript can request data from PHP without reloading the page.

Note: JavaScript can also run on servers through Node.js. The comparison above is about JavaScript in the browser, which is where beginners most often meet it.


Modern PHP

PHP has changed significantly over the years. Code written for PHP 5 often looks very different from modern PHP 8 code. The table shows the most important milestones.

VersionYearImportant Additions
PHP 7.02015Major performance improvement, scalar type declarations, return types, ?? operator
PHP 7.42019Typed properties, arrow functions, spread operator in arrays
PHP 8.02020Named arguments, union types, match, nullsafe operator ?->, attributes, constructor property promotion, JIT compiler
PHP 8.12021Enums, readonly properties, fibers, never return type, first-class callable syntax
PHP 8.22022Readonly classes, disjunctive normal form (DNF) types, true/false/null as standalone types
PHP 8.32023Typed class constants, #[\Override] attribute, json_validate()
PHP 8.42024Property hooks, asymmetric visibility, array_find() and related functions
PHP 8.52025Pipe operator |>, built-in URI extension, array_first() and array_last()

The Same Task in Older and Modern Style

Converting an order status code into a readable label:

Older style (switch):

<?php
function statusLabel($status)
{
    switch ($status) {
        case 'pending':
            return 'Waiting for payment';
        case 'paid':
            return 'Payment received';
        case 'shipped':
            return 'On the way';
        default:
            return 'Unknown status';
    }
}

echo statusLabel('paid');

Modern style (match, PHP 8.0+):

<?php
function statusLabel(string $status): string
{
    return match ($status) {
        'pending' => 'Waiting for payment',
        'paid'    => 'Payment received',
        'shipped' => 'On the way',
        default   => 'Unknown status',
    };
}

echo statusLabel('paid');

Output (both versions)

Payment received

What Changed and Why It Matters

  • string $status declares that the function expects a string, and : string declares that it returns one. If the wrong type is passed, PHP reports it immediately instead of producing a confusing result later.
  • match is an expression that returns a value directly, so there is no need for repeated return statements.
  • match uses strict comparison (===). switch uses loose comparison (==), which can match values of different types unexpectedly.
  • If no arm matches and there is no default, match throws an error instead of silently doing nothing. This makes mistakes visible.

You do not need to understand every detail yet — switch, match, and type declarations each have their own lessons. The point is that modern PHP gives you tools to write code that is shorter, safer, and easier to read. This tutorial teaches modern syntax first while still explaining older forms you will meet in existing projects.


When PHP Is a Good Fit — and When It Is Not

PHP is a strong choice for:

  • Content websites, blogs, and CMS-based sites
  • Business applications such as CRMs, ERPs, booking systems, and dashboards
  • E-commerce stores
  • REST APIs for web and mobile front ends
  • Projects that need inexpensive, widely available hosting

PHP is a weaker default choice for:

  • Long-lived real-time connections such as chat over WebSockets. The traditional request-based model is not built for connections that stay open for hours. It is possible with tools like Swoole, ReactPHP, or a separate service, but other platforms handle it more naturally.
  • Heavy numerical computing and machine learning, where Python's ecosystem is far more mature.
  • Desktop and mobile applications, which are normally built with other languages.

Choosing PHP for a web application is a practical, mainstream decision. Knowing its limits helps you design systems where PHP handles what it does best.


Common Misconceptions

"Visitors can see my PHP code."

On a correctly configured server, they cannot. The browser receives only the output. PHP source becomes visible only when the server is misconfigured and serves .php files as plain text — for example, when PHP is not installed or the web server is not set up to pass .php files to it. This is one reason passwords and API keys should be stored outside the public web folder, as explained in the PHP Security section.

"PHP is slow."

This reputation comes mostly from PHP 5. PHP 7 roughly doubled the speed of many real-world applications, and later versions continued to improve. In most web applications, the bottleneck is database queries and network calls, not the language itself.

"PHP is only for small websites."

Large platforms run on PHP. Facebook was originally built with it, and Wikipedia and WordPress.com still use it at a very large scale. Scalability depends on architecture — caching, database design, and infrastructure — much more than on the language.

"PHP can only make web pages."

PHP has a full command-line interface. You can write scheduled tasks, data-processing scripts, and command-line tools with it. The PHP Command Line (CLI) lesson covers this.


What You Need to Run PHP

To run the examples in this tutorial, you need:

  1. PHP installed on your computer (PHP 8.2 or newer recommended).
  2. A code editor such as Visual Studio Code or PhpStorm.
  3. A way to serve pages — PHP's built-in development server is enough while learning.

Later, for database lessons, you will also need MySQL or MariaDB.

The next lesson, PHP Install, walks through installation on Windows, macOS, Linux, and Docker.

Official reference: https://www.php.net/manual/en/intro-whatis.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
Ask about this post
AI Ask about this post

Ask questions about PHP Intro and get answers drawn from it.

Signed-in readers only.