Programming Languages
Modern PHP from syntax and forms to OOP, security, Composer, testing and production servers.
A path through modern PHP for people building web back ends: the language and its functions, forms, sessions and file handling, security basics, databases, object-oriented design, then the professional toolchain of Composer, tests, coding standards, static analysis, profiling and PHP-FPM. Each subject links the PHP manual or the tool's own documentation.
The subjects follow the roadmap.sh PHP roadmap.
PHP is a server-side scripting language built for the web: a request comes in, a script runs, HTML or JSON goes out, and the process forgets everything. Modern PHP (8.x) is typed, fast thanks to OPcache and JIT, and backed by a mature ecosystem around Composer, Laravel and Symfony.
An open-source, dynamically typed language usually run by a web server through PHP-FPM, though it also has a CLI for scripts and workers. Code sits inside <?php tags and can be mixed with HTML.
Started by Rasmus Lerdorf in 1994 as Personal Home Page tools, rewritten as the Zend Engine for PHP 4, given real objects in PHP 5, a big speed jump in PHP 7 and a typed, stricter language in PHP 8.
Each minor version gets two years of active support plus security fixes after that, so check the supported-versions page before choosing. PHP 8 brought named arguments, match, enums, readonly properties, fibers and property hooks.
Statements end with ;, variables start with $, and a file containing only PHP should omit the closing ?> so stray whitespace is never sent. Add declare(strict_types=1); at the top to stop silent scalar coercion.
Functions do not see outer variables: pass them as arguments, or for closures capture them with use. Arrow functions capture automatically by value; global and static locals exist but make code harder to test.
Scalars (int, float, string, bool), compound types (array, object, callable, iterable), plus null, enums and resources. Strings are byte strings, so use the mb_* functions for Unicode text.
Explicit casts like (int), (string) and (array), and implicit type juggling in comparisons. Use === to avoid surprises such as "abc" == 0 (false since PHP 8, true before).
Defined with const NAME = value; at compile time or define() at runtime, and never prefixed with $. Classes have their own constants, which can be typed and final in recent versions; magic constants like __DIR__ change by context.
Get PHP onto your machine via the OS package manager, Homebrew, Docker or an all-in-one bundle that also brings a web server and MySQL. For quick work, php -S localhost:8000 starts the built-in development server.
A cross-platform installer bundling Apache, MariaDB, PHP and Perl with a control panel. Convenient for beginners, but not hardened for production use.
Windows, Apache, MySQL and PHP; WampServer is the best-known bundle and makes switching PHP versions from the tray icon easy.
The macOS (and Windows) equivalent: Apache or Nginx, MySQL and several PHP versions in one app. Many Mac developers now prefer Homebrew, Docker or Laravel Herd.
Linux, Apache, MySQL/MariaDB and PHP installed from the distribution's packages: the classic production stack, often with Nginx and PHP-FPM replacing Apache today.
Sending text to the response and peeking at values while you work. Use echo for output and var_dump for inspection, and remember anything echoed into HTML must be escaped first.
A language construct, not a function, that writes one or more strings with no return value. <?= $x ?> is shorthand for echoing inside templates.
Like echo but takes exactly one argument and returns 1, so it can be used inside expressions. In practice echo is the usual choice.
Prints a value with its type and length, recursing into arrays and objects; the go-to for checking whether something is null, false or "". Xdebug makes its output prettier.
A more readable dump of arrays and objects without type details. Pass true as the second argument to get the string back, handy for logging.
PHP's array is an ordered hash map that serves as list, dictionary, set and stack all at once. The standard library has dozens of array_* functions such as array_map, array_filter, array_column and usort.
Arrays with integer keys from 0, written [1, 2, 3]. Removing an element with unset leaves a gap, so use array_values to reindex, and check array_is_list() when a real list matters.
String keys mapped to values, like ['name' => 'Ada']. Keys such as "1" become integers automatically. For structured data with a fixed shape, a class with typed properties is safer.
Arrays holding arrays, typical for rows from a database or decoded JSON. array_column pulls one field from every row, and the spread operator and destructuring help reshape them.
Branching in PHP: if, switch, the newer match expression and the operators that handle null gracefully. Prefer strict comparisons, because loose == follows the type-juggling rules.
Standard branching with if, elseif and else. The alternative syntax if (...): … endif; reads better inside HTML templates.
Compares one value against many case labels with loose ==, and falls through unless you break. Most new code uses match instead.
An expression (PHP 8) that returns a value, compares strictly, never falls through and throws UnhandledMatchError when nothing matches. Several conditions can share an arm with commas.
$a ?? $b returns $a unless it is null or undefined, without a warning, so it is ideal for $_GET['page'] ?? 1. ??= assigns only when the left side is null.
$user?->getAddress()?->city stops and returns null as soon as one link is null, replacing nested null checks. It works for reading, not for assigning.
PHP has for, while, do-while and foreach; foreach ($items as $key => $value) covers most needs. Iterating by reference with &$value leaves a live reference behind, so unset($value) afterwards. Generators with yield let you loop over large data without loading it all into memory.
Functions are declared with function, may carry parameter and return types, and can be passed around as values. PHP 8 added named arguments and the first-class callable syntax strlen(...).
Functions can be called before they are defined in the same file, and names are case-insensitive. Put them in namespaces and load them through Composer's files autoload rather than scattering includes.
Arguments pass by value (objects are handles, so they appear shared); prefix a parameter with & to pass by reference. Declare return types including void, never, nullable ?T and union types.
Give parameters defaults, like $limit = 10, and put them after required ones; an optional parameter before a required one is deprecated. Defaults must be constant expressions, though new is allowed since PHP 8.1.
Call with htmlspecialchars($s, double_encode: false) to skip defaults and document intent. Parameter names become part of your public API, so renaming one is a breaking change.
Closures are Closure objects you can store and pass. They capture outer variables only through use ($x), or use (&$x) by reference, and can be bound to another object with bind.
fn($x) => $x * $rate is a single-expression closure that captures outer variables by value automatically. Ideal for array_map and usort callbacks.
Anything callable: a closure, a function name string, [$obj, 'method'] or Class::method. The first-class syntax $obj->method(...) creates a closure that static analysers understand.
A function calling itself, natural for trees and nested arrays. PHP has no tail-call optimisation, so very deep recursion can exhaust memory; use an explicit stack or iterators for unbounded depth.
function sum(int ...$nums) collects remaining arguments into an array, and ...$array spreads an array into arguments at the call site. A variadic parameter can be typed and must be last.
Pulling one PHP file into another. In modern projects Composer's autoloader handles classes, so these are mostly left for bootstrap files, config arrays and templates.
Includes and runs a file, and stops with a fatal error if it is missing. Use it for files the script cannot work without; an included file can return a value, which makes $config = require 'config.php'; work.
Like require but skips a file already loaded, preventing redeclaration errors for functions and classes. It costs a lookup per call, which autoloading avoids.
Includes a file but only raises a warning when it is missing, so the script continues. Suitable for optional template parts; never build the path from user input.
The warning-only version of require_once: the file is included at most once per request.
Reading and writing local files and common data formats. Small files fit in one call; big ones should be streamed line by line with fopen and fgets or SplFileObject to keep memory flat.
file_get_contents reads a whole file into a string and file() into an array of lines. For large files open a handle with fopen and loop with fgets, checking every return value for false.
file_put_contents with FILE_APPEND and LOCK_EX covers most needs. For safe updates, write to a temporary file and rename() it into place so readers never see half a file.
Unix mode bits read and changed with fileperms, chmod, chown and is_writable. PHP-FPM runs as its own user, so upload and cache directories must be writable by it, never world-writable 0777.
fgetcsv and fputcsv handle quoting and embedded commas properly, which naive explode does not. Pass the escape parameter explicitly, since its default is changing, and watch for a UTF-8 byte-order mark from Excel.
json_encode and json_decode; pass true to decode into arrays and use JSON_THROW_ON_ERROR so invalid input throws instead of returning null silently. JsonSerializable controls how objects encode.
SimpleXML for quick reads, DOM for full manipulation, and XMLReader for streaming large documents. Do not load untrusted XML with external entities enabled.
Every PHP web request arrives with a method (GET, POST, PUT, DELETE…) and PHP exposes its parts through superglobal arrays available in every scope. GET should be safe to repeat; state changes belong in POST or other non-safe methods.
Query-string parameters, already URL-decoded. Values are strings or arrays (from ?tag[]=a), so validate the type before use, for example with filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT).
Form fields from application/x-www-form-urlencoded or multipart/form-data bodies only. For JSON bodies, read file_get_contents('php://input') and decode it yourself.
A merge of GET, POST and (depending on request_order) cookie data. Because you cannot tell where a value came from, prefer the specific arrays.
Server and request metadata: REQUEST_METHOD, REQUEST_URI, HTTP_* headers, REMOTE_ADDR. Header values come from the client, so never trust HTTP_HOST or HTTP_X_FORWARDED_FOR blindly.
The classic loop: render a form, receive the POST, validate every field, show errors with the user's input preserved, and on success redirect (Post/Redirect/Get) so a refresh does not resubmit. Escape values when echoing them back into the form.
HTTP is stateless and so is each PHP request, so anything that should survive between requests goes into cookies on the client or a session on the server. Configure both securely before storing anything about a user.
Set with setcookie() before any output, using the options array to set secure, httponly, samesite and an expiry. They arrive later in $_COOKIE; never store secrets or trust their contents without signing.
session_start() loads $_SESSION keyed by a cookie ID; by default data is stored in files on the server. Call session_regenerate_id(true) on login to prevent fixation, and use Redis or a database when you run several servers.
Uploaded files land in a temp location described by $_FILES and must be moved with move_uploaded_file(). Check the error code, enforce size limits (upload_max_filesize, post_max_size), detect the real type with finfo rather than trusting the client's, and store files outside the web root with generated names.
Most PHP vulnerabilities come from trusting input or forgetting to escape output. Validate on the way in, use parameterised queries, escape for the right context on the way out, and rely on the built-in password and random functions.
Check that every input has the type, length, format and range you expect, using an allow-list rather than a block-list. filter_var with FILTER_VALIDATE_INT or FILTER_VALIDATE_EMAIL covers common cases; frameworks add validator components.
Changing data so it is safe for a particular destination: escape for HTML, bind parameters for SQL, escapeshellarg for shell commands. Sanitise at output time for the target, rather than mangling input once on arrival.
Escape every dynamic value printed into HTML with htmlspecialchars($s, ENT_QUOTES, 'UTF-8') or a template engine that escapes by default, such as Twig or Blade. Add a Content-Security-Policy header as a second layer.
Never concatenate input into SQL. Use prepared statements with bound parameters in PDO or MySQLi; identifiers like column names cannot be bound, so check them against an allow-list.
Stops other sites from submitting forms as your logged-in user. Put a random per-session token (from random_bytes) in each form, compare it with hash_equals, and set SameSite on the session cookie.
Use password_hash($pw, PASSWORD_DEFAULT) and password_verify(); they handle salts and algorithm upgrades. Call password_needs_rehash on login to migrate old hashes. Never use md5 or sha1 for passwords.
Session-based login for classic sites, API tokens or JWTs for APIs, and OAuth 2 / OpenID Connect for social or single sign-on. Rate-limit login attempts and regenerate the session ID after authentication.
PHP talks to databases through extensions. PDO gives one API across many databases; MySQLi is MySQL-specific. Whichever you choose, use prepared statements and enable exceptions on errors.
The portable data-access layer with drivers for MySQL, PostgreSQL, SQLite and more. Create it with PDO::ERRMODE_EXCEPTION and a utf8mb4 charset, then prepare and execute with named or positional placeholders.
The MySQL-only extension with both procedural and object APIs, plus MySQL-specific features like multi-queries. Since PHP 8.1 it throws exceptions by default.
What production apps need beyond simple queries: transactions for consistency, ORMs for productivity, migrations for versioned schemas, and attention to connection handling and query performance.
Group writes with beginTransaction(), commit() and rollBack() in a try/catch so a failure leaves nothing half-done. MySQL's MyISAM tables ignore transactions; use InnoDB.
Map tables to classes: Doctrine uses the data-mapper pattern with entities separate from persistence, Eloquent in Laravel uses active record. Watch for N+1 queries and eager-load relations.
PHP has no in-process pool because each request is isolated. Options are persistent connections (PDO::ATTR_PERSISTENT), an external pooler like PgBouncer or ProxySQL, or long-running servers such as Swoole or RoadRunner.
Add indexes for your WHERE and JOIN columns, read query plans with EXPLAIN, select only needed columns, paginate with keyset rather than large offsets, and batch inserts. Most slow PHP pages are slow queries.
Versioned schema changes kept in code and applied in order, so every environment gets the same schema. Laravel, Doctrine Migrations and Phinx provide the tooling; make each migration reversible where you can.
Modern PHP code is object-oriented: classes with typed properties, interfaces, traits, enums and namespaces, loaded automatically by Composer. Frameworks are built on these features, so learn them before picking one.
Define a class, create instances with new, and use $this inside methods. Objects are passed by handle, so use clone (and __clone) when you need a copy.
__construct initialises an object; constructor property promotion (public function __construct(private Db $db) {}) declares and assigns in one go. __destruct runs when the last reference disappears, which is rarely needed.
Typed properties catch bad assignments; readonly properties can be set once from inside the class. Accessing an undeclared property creates a dynamic one, which is deprecated since PHP 8.2.
public, protected (class and subclasses) and private (this class only) on properties, methods and constants. Keep state private and expose behaviour, which makes refactoring safe.
Members that belong to the class, not an instance, accessed with ::. static:: uses late static binding to call the subclass's version. Static state is shared global state and hard to test, so use it sparingly.
A class extends one parent and can override its methods, calling parent::method() when needed. Mark classes or methods final to forbid extension, and prefer composition when the relation is not really "is a".
Code written against an interface or parent type works with any implementation, so the right behaviour is picked at runtime. Type-hint parameters with interfaces to swap implementations easily.
Classes that cannot be instantiated and may declare abstract methods subclasses must implement, while sharing concrete code. Use them when related classes share state and behaviour; otherwise an interface is lighter.
Contracts of public methods and constants that a class implements; a class can implement many. Built-in ones like Countable, IteratorAggregate, ArrayAccess and Stringable integrate your objects with the language.
Reusable sets of methods and properties copied into classes with use, working around single inheritance. Conflicts are resolved with insteadof and as; overusing traits hides dependencies.
Group code under names like App\Billing to avoid collisions, and import with use. With PSR-4 the namespace maps directly to the directory structure Composer's autoloader expects.
Hooks PHP calls for you: __toString, __get/__set for inaccessible properties, __call, __invoke, __serialize and others. Powerful for proxies and DSLs but they hide behaviour from IDEs and static analysers.
Pass collaborators in, usually through the constructor, instead of creating them inside the class. A container such as Symfony's or Laravel's, or PHP-DI, wires the graph automatically from type hints.
Types on parameters, returns and properties: scalars, classes, nullable ?T, unions A|B, intersections A&B, mixed, never and self. With strict_types=1 mismatched scalars throw TypeError instead of being coerced.
Frameworks supply routing, a service container, an ORM, templates, queues and security defaults so you do not rebuild them. Laravel and Symfony dominate the ecosystem; learning one makes the others easier because they share PSR standards and many components.
A framework plus a set of standalone components (HttpFoundation, Console, EventDispatcher) that many other projects, including Laravel, reuse. Configuration-driven, with a strong focus on long-term support releases.
A performance-focused framework with Gii code generation, active record and built-in caching. Yii 2 is widely deployed; Yii 3 is a rewrite built from separate packages.
Composer is PHP's dependency manager: composer.json lists requirements, composer.lock records exact versions, and vendor/autoload.php loads everything. Commit the lock file for applications so every deploy installs the same code.
Use composer require vendor/package, composer install in CI and deploys (from the lock file), and composer update only when you mean to upgrade. Scripts in composer.json work as a simple task runner.
The default public repository Composer resolves packages from. Publishing means pointing it at a public Git repository; versions come from Git tags.
Composer generates an autoloader from the autoload section, normally PSR-4 mapping a namespace prefix to a directory, so classes load on first use without require. Run composer dump-autoload -o for a faster class map in production.
Automated tests keep PHP's dynamic nature in check. PHPUnit is the foundation of the ecosystem and Pest builds a friendlier syntax on top of it; both run from Composer's vendor/bin.
The standard xUnit framework: test classes extending TestCase, assertions, data providers, test doubles and coverage via Xdebug or PCOV. Configured with phpunit.xml.
A testing framework on top of PHPUnit with closure-based test() and it() functions and an expect() API. Popular in the Laravel community, with plugins for architecture and mutation testing.
The PHP Framework Interop Group publishes shared standards so libraries and frameworks can work together. Its recommendations are why one logger, cache or HTTP client can plug into many different frameworks.
The ones you meet daily: PSR-4 autoloading, PSR-12 and PER Coding Style for formatting, PSR-3 logger, PSR-7 and PSR-17 HTTP messages, PSR-11 container, PSR-15 middleware and PSR-18 HTTP client.
Formatters and linters keep a codebase consistent and keep style arguments out of code review. Run them in CI and as a pre-commit hook, configured to the PSR-12 or PER style.
phpcs reports violations of a coding standard and phpcbf fixes what it can. Rulesets are XML, and many projects add custom sniffs.
A formatter that rewrites code to follow a rule set such as @PER-CS or @Symfony, configured in .php-cs-fixer.dist.php. Use --dry-run --diff in CI.
Static analysers read code without running it and catch type errors, null access and dead code, adding a compile step to a dynamic language. Start at a low level, keep a baseline for existing errors, and raise strictness over time.
The most widely used analyser, with levels 0 to 10, generics through PHPDoc annotations, a baseline file and framework extensions such as Larastan.
An analyser with strong type inference, taint analysis to trace user input into dangerous sinks, and automatic fixes through Psalter.
An analyser that prefers avoiding false positives, using the ast extension to parse code. Less common today than PHPStan or Psalm.
Step debuggers let you pause a request, inspect variables and walk the call stack instead of scattering var_dump. They connect from PHP to your IDE over the DBGp protocol.
The standard debugger extension: breakpoints with xdebug.mode=debug, stack traces, profiling and code coverage. It slows PHP down noticeably, so enable it only in development.
Zend's debugger extension, historically paired with Zend Studio. It is rarely used outside that toolchain now that Xdebug is supported by every major IDE.
Calling other services over HTTP: payment providers, APIs, webhooks. Always set timeouts, handle non-2xx responses and retries, and keep credentials out of the code.
The libcurl extension: curl_init, curl_setopt and curl_exec. It supports everything, but the API is verbose; set CURLOPT_TIMEOUT and CURLOPT_RETURNTRANSFER at minimum and check curl_errno.
The most popular HTTP client: a clean request API, middleware, concurrent requests through promises and PSR-7 and PSR-18 compatibility. Throws exceptions for 4xx and 5xx responses by default.
Making PHP apps fast: measure first, then cache aggressively (opcodes, data, HTTP responses), keep memory in check and tune the runtime. The biggest wins are usually OPcache, fewer queries and caching expensive results.
Find where time goes before optimising: Xdebug's profiler writes cachegrind files, while tools like Blackfire, Tideways or SPX give call graphs with less overhead and can profile production traffic.
Cache at several layers: APCu for per-server data, Redis or Memcached for shared data, and HTTP caching or a reverse proxy for whole pages. Plan invalidation and TTLs; PSR-6 and PSR-16 standardise the interfaces.
PHP frees values through reference counting plus a cycle collector, and releases everything at request end. Long scripts and workers should stream data with generators, unset big arrays, and watch memory_get_peak_usage().
Production php.ini and FPM settings: memory_limit, max_execution_time, realpath_cache_size, display_errors=Off, and FPM's pm.max_children sized to available RAM.
OPcache stores compiled scripts in shared memory so files are not reparsed on every request. In production set opcache.validate_timestamps=0 and reset the cache on deploy; preloading and JIT can help CPU-heavy code.
PHP running as a CLI script, worker or cron job needs to read configuration, run other programs and manage processes. Treat anything passed to the shell as an injection risk.
php.ini controls the runtime; php --ini shows which files are loaded, and FPM pools have their own config. Application config usually lives in PHP arrays, YAML or .env files read at boot.
Read with getenv() or $_ENV (only filled if variables_order includes E). Libraries like vlucas/phpdotenv load .env files in development; in production set real environment variables and never commit secrets.
exec, shell_exec, system and proc_open run external programs. Escape arguments with escapeshellarg, or pass an array to proc_open to bypass the shell; Symfony's Process component wraps this safely.
The pcntl extension forks processes and handles signals such as SIGTERM for graceful shutdown in long-running CLI workers. It is Unix-only and not available under a web server.
In production PHP sits behind a web server that serves static files and passes PHP requests on, usually through FastCGI to PHP-FPM. Point the document root at a public/ directory so source and config are never directly reachable.
An event-driven server that serves static files fast and forwards .php requests to PHP-FPM with fastcgi_pass. A try_files $uri /index.php?$query_string; line sends everything else to a front controller.
Long the default PHP host, either with mod_php inside Apache or with mod_proxy_fcgi to PHP-FPM. .htaccess files allow per-directory rewrites, at some performance cost.
The FastCGI process manager that keeps a pool of PHP workers ready. Choose pm = dynamic or static, size pm.max_children to memory, and enable the status page and slow log to spot problems.