Skip to content
PHP logo

PHP

First appeared 1995 · Rasmus Lerdorf

Powers a large share of the web — and the modern version is nothing like the one people remember.

Overview

PHP (PHP: Hypertext Preprocessor, a recursive acronym) is a widely-used, open-source, general-purpose scripting language that is especially well-suited for server-side web development and can be embedded directly into HTML. Created by Rasmus Lerdorf in 1994 and first released in 1995, PHP has grown to become one of the most popular server-side programming languages, powering a significant portion of the internet including some of the world's largest websites and web applications. PHP is executed on the server side, processing code and generating dynamic HTML content that is then sent to the client's web browser, making it ideal for creating dynamic, interactive, and data-driven websites. The language is known for its ease of use, gentle learning curve, extensive documentation, and massive ecosystem of frameworks, libraries, and tools that accelerate development. PHP features a syntax influenced by C, Java, and Perl, making it familiar to developers with experience in those languages. It supports multiple programming paradigms including procedural, object-oriented, and functional programming styles, giving developers flexibility in how they structure their code. PHP offers automatic memory management through reference counting and garbage collection, extensive built-in support for interacting with databases (MySQL, PostgreSQL, SQLite, and many others), file systems, sessions, cookies, and virtually every web-related task. The language includes a rich standard library with thousands of built-in functions for string manipulation, array operations, date and time handling, cryptography, image processing, XML parsing, and much more. PHP powers popular content management systems like WordPress (which runs over 40% of all websites), Drupal, and Joomla, e-commerce platforms like Magento and WooCommerce, and frameworks like Laravel, Symfony, and CodeIgniter that provide structure and tools for building modern web applications. The language runs on virtually every operating system and web server, making it highly portable and accessible. PHP's integration with HTML is seamless, allowing developers to mix PHP code directly within HTML markup, though modern best practices encourage separation of concerns. The language has evolved significantly over its lifetime, with major versions introducing substantial improvements in performance, security, and features. PHP 7, released in 2015, brought dramatic performance improvements (often 2-3x faster than PHP 5), reduced memory consumption, and new language features. PHP 8, released in 2020, introduced JIT (Just-In-Time) compilation for even better performance, union types, named arguments, attributes, and many other modern language features. Despite facing criticism over the years for inconsistencies in its standard library and some design decisions from its early days, PHP has continuously evolved and modernized, addressing many historical concerns while maintaining backward compatibility. The language has a massive, active community, extensive learning resources, and countless hosting providers offering PHP support out of the box, making it one of the most accessible languages for web development.

Key facts

The reference details, without the paragraph.

First appeared
1995
Designed by
Rasmus Lerdorf, later shaped by Zeev Suraski and Andi Gutmans
Typing
Dynamic and gradual — optional type declarations checked at runtime, strict mode available
Execution
Compiled to opcodes and executed by the Zend Engine, with an opcode cache and a JIT since PHP 8
Memory model
Automatic — reference counting plus a cycle collector; state is discarded after each request
Package manager
Composer, backed by Packagist
File extensions
.php
Current line
PHP 8.4, with 8.x releases each November
Execution model
Shared-nothing per request — each request starts clean, which makes horizontal scaling trivial
Licence
PHP License (BSD-style)

History

How the language got here — the decisions that still shape how you write it.

PHP was created by Rasmus Lerdorf, a Danish-Canadian programmer, in 1994 as a set of Common Gateway Interface (CGI) binaries written in C to track visits to his online resume and personal homepage. Originally called 'Personal Home Page Tools' (PHP Tools), it was a simple set of scripts for basic web page functionality. Lerdorf released the source code publicly in 1995, allowing other developers to use and modify it, which led to community contributions and improvements. The early version, known as PHP/FI (Personal Home Page / Forms Interpreter), was released in 1997 and included basic functionality for building dynamic web pages and processing form data. However, PHP/FI was limited in scope and not designed as a full programming language. The turning point came in 1998 when two Israeli developers, Andi Gutmans and Zeev Suraski, rewrote the PHP parser from scratch, creating PHP 3. This version transformed PHP from a simple tool into a serious programming language with support for multiple databases, extensibility through modules, and a more consistent syntax. PHP 3 was released in June 1998 and marked the beginning of PHP's rapid growth in popularity. Gutmans and Suraski continued their work, developing the Zend Engine, a new scripting engine that would power PHP 4, released in May 2000. The Zend Engine significantly improved performance, added support for more advanced programming features, and established PHP as a professional-grade language for web development. The name 'Zend' came from combining their first names (Zeev and Andi). PHP 4 saw massive adoption, becoming the dominant server-side language for web development during the early 2000s. PHP 5, released in July 2004, was another major milestone, introducing a completely rewritten object-oriented programming model with classes, interfaces, abstract classes, and other OOP features that brought PHP in line with languages like Java and C#. This version also introduced the PHP Data Objects (PDO) extension for database access, improved XML support, and better error handling through exceptions. PHP 5 remained the primary version for over a decade, with incremental updates adding features like namespaces, late static binding, closures, and traits. The development of PHP 6 was attempted but ultimately abandoned due to challenges with Unicode implementation. Instead, the community moved forward with PHP 7, which was released in December 2015 and represented a massive leap forward. PHP 7 was built on a new version of the Zend Engine (PHPNG - PHP Next Generation) that dramatically improved performance, often making applications 2-3 times faster while using less memory. This performance improvement was crucial for PHP's continued relevance in an era of increasing competition from Node.js and other technologies. PHP 7 also introduced scalar type declarations, return type declarations, the null coalescing operator, and other modern language features. The version number jumped from 5 to 7 to avoid confusion with the abandoned PHP 6. PHP 7.x continued to evolve with several minor releases adding features like nullable types, void return types, and improved error handling. PHP 8.0, released in November 2020, brought another major evolution with JIT compilation, union types, named arguments, attributes (similar to annotations in other languages), match expressions, constructor property promotion, and many other improvements. PHP 8.1 and subsequent versions have continued adding features like enums, readonly properties, and fibers for improved async programming. Throughout its history, PHP has powered some of the internet's most significant platforms. Facebook was originally built entirely in PHP, and while they've since created Hack (a PHP dialect) and HHVM (an alternative runtime), PHP remains at the core of their infrastructure. WordPress, the world's most popular content management system, is written in PHP and powers over 40% of all websites on the internet. Wikipedia, Slack, Etsy, MailChimp, and countless other major platforms rely on PHP. The language has faced criticism over the years for inconsistencies in its standard library (function naming conventions, parameter orders), weak typing leading to unexpected behavior, and security issues in poorly written code. However, the PHP community has worked diligently to address these concerns, with modern PHP being a much more consistent, secure, and performant language. The PHP-FIG (PHP Framework Interop Group) has established PSR (PHP Standards Recommendations) that provide coding standards and interoperability guidelines, improving consistency across the ecosystem. Modern PHP frameworks like Laravel have brought elegant syntax, powerful features, and best practices to PHP development, making it competitive with frameworks in other languages. Composer, PHP's dependency manager introduced in 2012, revolutionized how PHP developers manage libraries and dependencies. Today, PHP continues to be actively developed with regular releases, a strong commitment to backward compatibility, and a focus on performance and modern language features. While newer languages and technologies have emerged, PHP's massive installed base, mature ecosystem, ease of deployment, and continuous evolution ensure it remains a vital part of the web development landscape.

  1. 1995

    Personal Home Page tools

    Rasmus Lerdorf writes a set of CGI scripts in C to track visits to his online CV. He releases them, other people use them, and a language accretes around them — which explains a great deal about early PHP's design.

  2. 1997–1998

    PHP 3 and the Zend Engine

    Zeev Suraski and Andi Gutmans rewrite the parser. PHP 4 follows with the Zend Engine, and the language becomes fast enough for serious traffic.

  3. 2004

    PHP 5 and real object orientation

    Proper classes, interfaces, exceptions, and later namespaces and closures. This is when PHP becomes capable of large applications rather than page scripts.

  4. 2012

    Composer and PSR standards

    Composer brings dependency management and PSR-4 autoloading; the PHP-FIG group standardises interfaces across frameworks. Arguably the most important development in PHP's history — the ecosystem becomes shareable.

  5. 2015

    PHP 7 doubles performance

    A rewritten engine roughly halves memory use and doubles throughput, adds scalar type declarations and return types, and makes the null coalescing operator standard.

  6. 2020

    PHP 8

    A JIT compiler, named arguments, attributes, constructor property promotion, union types, `match` expressions and nullsafe operators. The language modernises substantially in one release.

  7. 2023–2025

    Continued maturation

    Readonly classes, enums, fibers for cooperative concurrency, property hooks and asymmetric visibility. Static analysis with PHPStan and Psalm becomes standard practice on serious projects.

What it is good at

The reasons teams pick it, stated concretely.

  • The shortest path from code to a working website

    Deployment can be as simple as copying files to a server. Shared hosting, cPanel and one-click installs mean PHP powers an enormous long tail of the web that never touches a build pipeline.

  • Shared-nothing execution is quietly brilliant

    Each request starts with a clean slate and everything is discarded afterwards. Memory leaks cannot accumulate across requests, and scaling out is a matter of adding servers — no session affinity, no shared process state.

  • Laravel and Symfony are genuinely excellent

    Routing, ORM, queues, caching, authentication, testing and background jobs, all cohesive and well documented. Laravel's developer experience is competitive with anything in any language.

  • PHP 8 is fast

    The PHP 7 rewrite doubled throughput and PHP 8's JIT went further. For typical request-response web workloads it comfortably outperforms Python and Ruby.

  • An enormous installed base

    WordPress alone runs a large fraction of all websites. Whatever else is true, there is a great deal of PHP work, and much of it is well paid maintenance and modernisation.

Trade-offs

Every language costs you something. Knowing what, before you commit, is the whole point.

  • An inconsistent standard library

    `strpos` versus `str_contains`, needle-haystack argument orders that vary by function, and underscores that appear in some names and not others. Thirty years of accretion, kept for backwards compatibility.

  • A reputation earned by PHP 4

    Register globals, `mysql_query` with string concatenation, and a generation of tutorials teaching SQL injection by example. The language moved on; the reputation is slower.

  • Type checking is runtime, not compile time

    Type declarations throw when violated rather than preventing the build. PHPStan and Psalm recover most of the value through static analysis, but they are third-party and opt-in.

  • Weak fit outside web request handling

    The shared-nothing model that suits HTTP works against long-running processes, desktop applications, data science and systems work. Fibers and Swoole help; they are not the mainstream.

  • Legacy code you will meet

    A large share of production PHP predates Composer, namespaces and type declarations. Modernising a codebase where business logic lives inside HTML templates is a specific and common kind of hard.

Code examples

Not syntax tours — the idioms that make code read like the language rather than a translation of another one.

Modern PHP: types, promotion, readonly
<?php
declare(strict_types=1);   // put this at the top of every file

final class Invoice
{
    // Constructor property promotion — no repeated field declarations.
    public function __construct(
        public readonly string $id,
        public readonly string $customer,
        public readonly float  $amount,
        public readonly ?string $notes = null,
    ) {
        if ($amount < 0) {
            throw new InvalidArgumentException('amount must not be negative');
        }
    }

    public function withAmount(float $amount): self
    {
        return new self($this->id, $this->customer, $amount, $this->notes);
    }
}

$invoice = new Invoice(id: 'INV-1', customer: 'Ada', amount: 250.00);
`strict_types=1` stops PHP silently coercing `"5"` into `5`, which is the single most valuable line in a modern PHP file. `readonly` properties cannot be changed after construction, and named arguments make long signatures readable at the call site.
Enums and match expressions
<?php
enum OrderStatus: string
{
    case Pending   = 'pending';
    case Shipped   = 'shipped';
    case Delivered = 'delivered';
    case Cancelled = 'cancelled';

    public function isFinal(): bool
    {
        return match ($this) {
            self::Delivered, self::Cancelled => true,
            self::Pending, self::Shipped     => false,
        };
    }
}

$status = OrderStatus::from('shipped');   // throws on an unknown value
$maybe  = OrderStatus::tryFrom('unknown'); // null instead of throwing

var_dump($status->isFinal());   // bool(false)
Backed enums replace class constants and stringly-typed status fields, and `match` is exhaustive and strictly compared — unlike `switch`, which uses loose comparison and falls through by default. Together they remove a real source of bugs.
Database access without SQL injection
<?php
$pdo = new PDO(
    'mysql:host=localhost;dbname=shop;charset=utf8mb4',
    $user,
    $password,
    [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]
);

// Placeholders — the value never becomes part of the SQL text.
$statement = $pdo->prepare(
    'SELECT id, total FROM orders WHERE customer = :customer AND total > :min'
);
$statement->execute(['customer' => $customerInput, 'min' => 100]);

foreach ($statement as $row) {
    echo $row['id'], ': ', $row['total'], PHP_EOL;
}
Those three PDO options should be your default: exceptions instead of silent failures, associative arrays instead of duplicated columns, and real prepared statements instead of client-side emulation. String-concatenated SQL is how PHP earned its security reputation — prepared statements are how you avoid it entirely.
Arrays and the functional toolkit
<?php
$orders = [
    ['region' => 'EU', 'total' => 120.0],
    ['region' => 'US', 'total' => 340.0],
    ['region' => 'EU', 'total' => 80.0],
];

$byRegion = array_reduce(
    $orders,
    function (array $carry, array $order): array {
        $carry[$order['region']] ??= 0.0;
        $carry[$order['region']] += $order['total'];
        return $carry;
    },
    []
);

arsort($byRegion);
print_r($byRegion);   // ['US' => 340.0, 'EU' => 200.0]

// First-class callable syntax (PHP 8.1)
$totals = array_map(fn (array $o): float => $o['total'], $orders);
echo array_sum($totals);   // 540
PHP arrays are ordered hash maps that serve as both list and dictionary, which is why almost every built-in function takes one. `??=` assigns only when the key is unset, avoiding the `isset` check that used to precede this pattern.

Common pitfalls

The mistakes that cost everyone an afternoon at least once.

  • Building SQL by concatenating input

    `"SELECT * FROM users WHERE id = $id"` is the SQL injection that made PHP infamous. Always use prepared statements with placeholders, and disable `ATTR_EMULATE_PREPARES`.

  • Echoing user input without escaping

    Any unescaped value in HTML is a cross-site scripting hole. Use `htmlspecialchars` with `ENT_QUOTES`, or a template engine such as Blade or Twig that escapes by default.

  • Loose comparison with `==`

    PHP's type juggling makes surprising things equal. Use `===` and `!==` unless you have a specific reason, and use `match` rather than `switch`, which compares loosely.

  • Hashing passwords by hand

    `md5` and `sha1` are not password hashes. Use `password_hash` and `password_verify`, which handle salting and algorithm upgrades for you.

  • Suppressing errors with `@`

    The error suppression operator hides the message and leaves the failure. Configure error reporting properly and handle exceptions instead.

  • Following outdated tutorials

    `mysql_*` functions were removed in PHP 7, `register_globals` is long gone, and a lot of highly-ranked search results still teach both. Check the publication date and prefer the official documentation.

In production

Where it is running at scale, and what it is doing there.

  • Facebook (Meta)

    Backend services and web applications (originally built with PHP).

  • WordPress

    Content management system powering 40% of websites.

  • Slack

    Backend API services and web applications.

  • Etsy

    E-commerce platform and marketplace backend.

Learning path

A realistic order to learn things in, with something to build at each step.

  1. 1

    Week 1

    Language basics, modern style

    Variables, types, arrays, functions, control flow, and `declare(strict_types=1)`. Follow current documentation — a great deal of PHP material online is fifteen years out of date and teaches insecure patterns.

    Build this: Build a script that reads a CSV, validates the rows and prints a summary.

  2. 2

    Weeks 2–3

    Object orientation and Composer

    Classes, interfaces, traits, namespaces, exceptions, enums, and Composer with PSR-4 autoloading. Composer is the dividing line between modern PHP and the old way.

    Build this: Restructure your script as a Composer package with classes, autoloading and PHPUnit tests.

  3. 3

    Weeks 4–6

    The web layer, done safely

    Request handling, sessions, PDO with prepared statements, password hashing with `password_hash`, input validation and output escaping. Understand SQL injection and XSS properly — this is where PHP applications historically fail.

    Build this: Build a small CRUD application with authentication, without a framework, so you see what the framework does for you.

  4. 4

    Months 2–3

    A framework

    Laravel or Symfony: routing, dependency injection, ORM (Eloquent or Doctrine), migrations, queues, caching and testing. Learn what problem each component solves rather than memorising the API.

    Build this: Rebuild your CRUD app in Laravel with migrations, form requests and feature tests.

  5. 5

    Ongoing

    Professional practice

    PHPStan or Psalm at a high level, PHP-CS-Fixer, Xdebug for step debugging, OPcache and JIT tuning, and queue workers for background jobs.

    Build this: Run PHPStan at level 8 on an existing project and fix what it finds.

Ecosystem and tooling

The tools you will end up installing whichever project you join.

ToolWhat it does
ComposerDependency management and autoloading; the foundation of the modern ecosystem
LaravelThe most popular framework — batteries included, exceptional documentation and developer experience
SymfonyComponent-based framework favoured for large and long-lived enterprise applications
PHPStan / PsalmStatic analysis that catches type errors before runtime; effectively mandatory on serious projects
PHPUnit / PestTesting — PHPUnit is the standard, Pest offers a lighter expressive syntax on top of it
XdebugStep debugging, profiling and code coverage
Doctrine / EloquentData mapper and active record ORMs; Doctrine for complex domains, Eloquent for speed of development
OPcache / JITBuilt-in opcode caching and just-in-time compilation — enable OPcache in production, always

PHP libraries

10 catalogued, each with installation, worked examples and best practices.

Frequently asked

Is PHP dead?

No — it runs a large share of the web, including WordPress, and the job market for it is substantial. It has lost mindshare for new greenfield startups, where JavaScript and Python dominate, but 'not fashionable' and 'not used' are different things. PHP 8 is a genuinely good language.

Is modern PHP really that different?

Yes. Type declarations, enums, readonly properties, match expressions, attributes, constructor promotion, Composer, PSR standards and static analysis at level 8 produce code that looks nothing like PHP 5. If your impression comes from 2010, it is out of date.

Laravel or Symfony?

Laravel for speed of development, a gentler learning curve and a rich first-party ecosystem — it is the default choice for most new projects. Symfony for large, long-lived applications where its component architecture and stricter conventions pay off. Laravel is built on Symfony components, so the knowledge overlaps.

Should I learn PHP to work with WordPress?

If WordPress development is the goal, yes — themes, plugins and hooks are all PHP. Be aware that WordPress's own codebase predates modern PHP conventions by a long way, so learn current PHP separately rather than absorbing its style as a model.

How fast is PHP compared with Node or Python?

For request-response web workloads PHP 8 is competitive with Node.js and comfortably faster than Python or Ruby. Where it differs is the model: PHP restarts per request rather than keeping a long-lived process, which trades some raw throughput for excellent isolation and simple scaling.

Can PHP handle real-time features like WebSockets?

Not naturally in the standard model, since each request ends. Swoole, ReactPHP and Laravel Reverb provide long-running event-driven servers, and they work — but if real-time is central to your product, Node.js, Go or Elixir are better-trodden paths.