PHP Roadmap

PHP is the server-side language behind a large share of the web, including WordPress, Drupal and many long-running business systems, and it is also the base of modern frameworks such as Laravel and Symfony. Jobs that ask for PHP range from maintaining older code to building new APIs on current versions.

This roadmap takes you from installing PHP to being ready for junior and mid-level interviews. It follows the order people actually learn in: the language, functions and arrays, object-oriented code, the web layer, databases and Composer, security, testing and finally performance and production. Each topic is explained in the text, with a short exercise.

Modern PHP (version 8 and later) is a typed, expressive language with enums, attributes, readonly properties and strong tooling. The roadmap teaches that version, and points out older habits you will still meet in existing code. By the end you will be able to build a small web application without a framework, explain how it works, and secure and test it.

Level
Beginner to advanced
Time
12–16 weeks at about 8 hours a week
Scope
64 topics in 10 stages
Before you start
Basic HTML, enough to write a form and a page; Comfort using a terminal and a code editor; Optional: SQL Roadmap basics, which you will need from the database stage

What you will be able to do

  • Write typed, readable PHP 8 code using functions, arrays, classes, interfaces and enums
  • Build a form-driven web application with sessions, file uploads and a database using PDO
  • Manage dependencies and autoloading with Composer and follow PSR conventions
  • Prevent SQL injection, XSS and CSRF and store passwords correctly
  • Test code with PHPUnit or Pest and catch bugs with static analysis
  • Configure PHP-FPM, OPcache and caching for production and profile slow code
  • Explain core PHP and OOP concepts clearly in an interview

The roadmap at a glance

  1. Stage 1Getting Started with PHPBeginner · 1 week · 9 topics
  2. Stage 2Language FundamentalsBeginner · 2 weeks · 8 topics
  3. Stage 3Functions and ArraysBeginner · 2 weeks · 7 topics
  4. Stage 4Object-Oriented PHPIntermediate · 2–3 weeks · 6 topics
  5. Stage 5Advanced Language FeaturesIntermediate · 2 weeks · 5 topics
  6. Stage 6PHP on the WebIntermediate · 2–3 weeks · 6 topics
  7. Stage 7Databases and DependenciesIntermediate · 2–3 weeks · 7 topics
  8. Stage 8SecurityIntermediate · 2 weeks · 6 topics
  9. Stage 9Testing, Quality and DebuggingIntermediate · 2 weeks · 4 topics
  10. Stage 10Performance, Production and the Wider EcosystemAdvanced · 3 weeks · 6 topics

Stage 1 Getting Started with PHP

Beginner1 week9 topics

Goal. Install PHP, run a script from the command line and in a browser, and explain what happens on the server when a request arrives.

What is PHP? Core

PHP is a general-purpose scripting language built for the web. A PHP file is mixed with HTML: anything outside the <?php ... ?> tags is sent to the browser as it is, and anything inside is executed first.

PHP code runs on the server, not in the browser. The visitor never sees your PHP, only the output it produced. Each request normally starts a fresh run: variables from the last request are gone unless you saved them in a session, a file or a database.

PHP powers WordPress, Drupal, Magento and much of the older web, and it is also used in new projects built on Laravel and Symfony. See Laravel Roadmap for that framework and WordPress Roadmap for the CMS.

Practice. Write down, in five sentences, what happens between typing a URL and seeing a page that PHP generated.

Introduction to PHP Core

A minimal PHP script looks like this:

<?php
$name = 'Asha';
echo "Hello, $name";

Statements end with a semicolon. Files that contain only PHP should omit the closing ?> tag, which avoids accidental whitespace being sent before headers. Comments use //, # or /* ... */.

PHP is dynamically typed with optional type declarations, interpreted at run time (compiled to opcodes in memory) and case-sensitive for variables but not for function names. Most real code today starts with declare(strict_types=1); and works inside classes, though the language still allows quick procedural scripts.

Practice. Create hello.php, run it with the built-in command line, then change it to print today's date.

Evolution and History Optional

PHP began in the mid-1990s as a set of small tools for personal home pages and grew into a full language. Early versions had inconsistent function names and argument orders, which is why you still see strpos($haystack, $needle) beside array_search($needle, $haystack). These quirks stay for backwards compatibility.

The major shifts were object orientation (PHP 5), namespaces, closures and Composer (the 5.3 to 5.6 era), big speed gains and scalar type declarations (PHP 7), and a modern feature run from PHP 8 onwards: attributes, enums, readonly properties, match, fibers and more.

Knowing the history helps in interviews because it explains why legacy code looks so different from modern code, and why PHP's reputation lags behind its present state.

Practice. Open an old tutorial snippet and list three things in it that modern PHP would write differently.

PHP Versions and Features Core

PHP releases a new minor version about once a year, and each version gets active support for roughly two years and security fixes for a further period. Running a version past its end of life means no security patches, so check the official support table before choosing a version for a project.

Features worth knowing by version family:

  • PHP 7: scalar types, return types, the null coalescing operator, the spaceship operator.
  • PHP 8.0: named arguments, constructor promotion, union types, match, the null safe operator, attributes.
  • PHP 8.1 and later: enums, readonly properties, first-class callable syntax, never return type, and more refinements in each release.

Do not memorise exact release dates. Learn what each feature does and which ones your target job's version allows.

Practice. Pick three features from the list above and rewrite one old-style snippet using each of them.

Installing PHP Core

You need the PHP interpreter, a way to run it, and ideally Composer. On macOS, a package manager such as Homebrew installs PHP in one command; on Linux, use your distribution's packages or a trusted third-party repository for newer versions; on Windows, use the official zip or WSL.

Check the install with php -v and list loaded extensions with php -m. The configuration file is php.ini; php --ini shows which one is active. Command line PHP and web PHP often use different ini files, which is a common source of confusing bugs.

The quickest development server needs no web server setup at all:

php -S localhost:8000 -t public

Use it for learning only. Production runs behind Apache or Nginx.

Practice. Install PHP, run php -v and php -m, then serve a folder with the built-in server and open it in a browser.

LAMP, WAMP, MAMP and XAMPP Recommended

LAMP means Linux, Apache, MySQL (or MariaDB) and PHP: the classic hosting stack. WAMP is the same idea on Windows, MAMP on macOS, and XAMPP is a cross-platform bundle that adds Perl and a database in one installer.

These bundles are fine for beginners because everything is preconfigured, but they hide how the parts connect. Many teams now use Docker Compose with separate PHP, web server and database containers so that every developer and the server run the same versions.

Learn at least once how to wire the pieces by hand: a web server receives the request, hands PHP files to PHP-FPM, and PHP talks to the database.

Practice. Set up either a bundle or a Docker Compose file that serves a PHP page which prints the database server version.

Apache and Nginx Core

PHP does not listen on the internet itself. A web server does, and it passes requests for PHP files on.

Apache can embed PHP as a module, but most modern setups use PHP-FPM with either server. Apache reads per-directory .htaccess files, which is convenient for shared hosting and for pretty URLs. Nginx has no .htaccess; you put rewrite rules in the main configuration and forward PHP requests to the FPM socket with fastcgi_pass.

The usual front-controller pattern sends every request that is not a real file to public/index.php. Both servers need a rule for this. Keep the document root pointed at public, never at the project root, so that source files and .env cannot be downloaded.

Practice. Configure a virtual host so that any unknown path is routed to public/index.php and prints the requested path.

Basic PHP Syntax Core

Variables start with $, need no declaration and are case-sensitive. Strings in single quotes are literal; double quotes expand variables and escapes such as \n. Heredoc and nowdoc syntax handle long text.

$price = 9.99;
$label = "Total: {$price}";
$items = ['tea', 'coffee'];

Statements end with ;, blocks use braces, and <?= $x ?> is a short echo for templates. Mixing HTML and PHP is allowed, but keep logic out of templates: compute values first, then output them.

Always escape output headed to HTML. That habit starts here, not in the security chapter.

Practice. Write a script that builds a greeting from three variables using single quotes, double quotes and heredoc.

Output and Debugging Basics: echo, print, print_r and var_dump Core

echo outputs one or more strings and is a language construct, not a function. print does the same for a single value and returns 1, so it is rarely used.

For debugging, print_r($value) gives a readable dump of arrays and objects, while var_dump($value) also shows types and sizes, which exposes bugs such as "1" versus 1, or false versus null. Wrap print_r in <pre> tags in a browser, and pass true as the second argument to get the text back instead of printing it.

These are quick tools. For real debugging, a step debugger such as Xdebug is far better, and logs should go through error_log or a logging library, not the page.

Practice. Dump the same mixed array with print_r and var_dump and write down what var_dump shows that print_r does not.

Stage 2 Language Fundamentals

Beginner2 weeks8 topics

Goal. Write correct scripts that store, test, loop over and combine data using PHP's core types and control structures.

Variables and Scope Core

A variable defined inside a function exists only inside that function. A variable defined at the top of a file is global, but functions cannot see it unless you pass it in, import it with the global keyword or read $GLOBALS. Prefer passing arguments.

A static variable inside a function keeps its value between calls. Closures capture outer variables with use, by value unless you write &. Arrow functions capture the whole surrounding scope by value automatically.

Variable variables ($$name) and extract() are legal but make code hard to follow and are best avoided.

Practice. Write a counter function with a static variable, then rewrite it as a closure that captures its count by reference.

Data Types Core

PHP's scalar types are int, float, string and bool. The compound types are array and object, plus callable and iterable. null is its own type meaning no value.

Integers have a platform-dependent maximum and silently become floats on overflow. Floats are binary, so 0.1 + 0.2 == 0.3 is false; compare with a tolerance or use integer cents or the BCMath extension for money.

Strings are byte arrays. Use the mb_* functions (mb_strlen, mb_substr) for UTF-8 text, otherwise strlen('é') returns 2.

Use gettype() or get_debug_type() to inspect a value, and === rather than == to compare without surprises.

Practice. Predict, then run, the results of five loose comparisons such as 0 == "a" and "1" == "01", and explain each result.

Casting Data Types Core

PHP converts between types automatically (type juggling) and explicitly with casts such as (int), (string), (float), (bool) and (array). Functions like intval() do the same.

var_dump((int) '42abc');   // int(42)
var_dump((bool) '0');      // bool(false)
var_dump((bool) []);       // bool(false)

The falsy values are false, 0, 0.0, '', '0', [] and null. Numeric strings are the trap: 'abc' == 0 changed behaviour in PHP 8, so older tutorials may be wrong.

With declare(strict_types=1) at the top of a file, scalar type declarations on function calls stop coercing silently and throw TypeError instead.

Practice. Cast ten odd values to bool and int and note which ones surprise you.

Constants Recommended

A constant is a name bound to a value that cannot change. Define one with const MAX_ITEMS = 10; at file level or inside a class, or with define('MAX_ITEMS', 10) when the name is computed at run time. Constants have no $ and are global unless inside a class or namespace.

Class constants (Order::STATUS_PAID) group related values and can carry visibility modifiers. Since PHP 8.1 you can mark them final, and enums are usually better than a pile of related string constants.

Magic constants such as __FILE__, __DIR__, __LINE__ and __CLASS__ change meaning depending on where they appear and are useful for building paths and log messages.

Practice. Replace three loose status strings in a script with a class constants block and then with a backed enum.

Operators, Null Coalescing and Null Safe Core

Beyond arithmetic and comparison, learn these operators:

  • ?? returns the left side if it exists and is not null, else the right side: $page = $_GET['page'] ?? 1;
  • ??= assigns only when the variable is unset or null.
  • ?-> is the null safe operator: $user?->profile?->city stops and returns null if any link is null.
  • <=> is the spaceship operator, returning -1, 0 or 1, handy in sort callbacks.
  • ?: is the short ternary, which tests truthiness rather than null.

Prefer === and !==. Remember that && and || bind tighter than and and or, which causes assignment surprises.

Practice. Rewrite a block of isset() checks and nested ifs using ?? and ?-> and compare the length.

Conditionals: if/else, switch and match Core

if, elseif and else handle most branching. switch compares with loose equality and falls through unless you break, which has caused many bugs.

match (PHP 8) is an expression that uses strict comparison, returns a value, needs no break and throws UnhandledMatchError if nothing matches and there is no default.

$label = match (true) {
    $score >= 90 => 'A',
    $score >= 70 => 'B',
    default => 'C',
};

Use early returns to avoid deep nesting: check the failure cases first and leave, so the main path stays at the left margin.

Practice. Convert a switch statement into a match expression and add a case that triggers the UnhandledMatchError.

Loops Core

PHP offers for, while, do ... while and foreach. foreach is the one you use most because it walks arrays and iterable objects directly: foreach ($items as $key => $item).

Modifying an array while looping over it by value is safe because you get a copy, but taking a reference (&$item) leaves the reference alive after the loop, so call unset($item) afterwards. break and continue accept a number to leave nested loops.

For large data, generators (yield) produce values one at a time and keep memory flat. Reading a million-line file with a generator uses a tiny fraction of the memory of loading it into an array.

Practice. Write a generator that yields lines of a large file and sums a column without loading the whole file.

include, include_once, require and require_once Core

These pull another file into the current script. require stops the script with a fatal error when the file is missing; include only emits a warning and carries on. The _once forms skip the file if it was already loaded, which prevents redeclaring functions or classes.

Use require for things the script cannot work without, and include for optional fragments. Paths are resolved relative to the include path and the calling script's directory in confusing ways, so build absolute paths with __DIR__ . '/config.php'.

In modern applications you rarely include class files by hand. Composer's autoloader loads classes on demand, and you require only vendor/autoload.php once.

Practice. Split a script into config.php and functions.php, load them with require_once, and observe what happens when one is missing.

Stage 3 Functions and Arrays

Beginner2 weeks7 topics

Goal. Write reusable, typed functions and shape data with arrays and callbacks without reaching for loops every time.

Arrays: Indexed, Associative and Multi-dimensional Core

A PHP array is an ordered map, used as list, dictionary, set or stack. Indexed arrays use integer keys: $a = ['x', 'y'];. Associative arrays use string keys: $user = ['name' => 'Asha', 'age' => 30];. Multi-dimensional arrays nest arrays inside arrays, as in rows of records.

Arrays are copied on assignment (lazily, so it is cheap), unlike objects, which are handles. Useful tools include array_map, array_filter, array_column, array_merge, the spread operator [...$a, ...$b] and array_key_exists. Use isset or ?? to read keys that may not exist.

Sorting has many variants: sort, asort, ksort and usort with a callback. Check whether a function sorts in place or returns a new array.

Practice. Given an array of order records, group them by customer and compute the total per customer.

Function Declaration and Recursion Core

function slug(string $title): string
{
    return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($title)), '-');
}

Functions are declared with function, can appear anywhere in a file that is loaded, and live in the global namespace unless you declare a namespace. Names are case-insensitive but you should still be consistent.

Good functions are small, do one thing, and avoid hidden inputs such as globals. A function with an unclear name or six parameters is a sign that it should be split or turned into a class.

A function can call itself (recursion) when a problem has nested structure, such as a directory tree. It needs a base case, and very deep recursion exhausts memory, so use an explicit stack for large inputs.

Practice. Write three small helper functions (slug, truncate, money format) with full type declarations.

Parameters, Return Values and Default Parameters Core

Parameters are passed by value by default; prefix with & to pass by reference, which is occasionally useful (sort does it) but easy to abuse. Optional parameters take a default: function greet(string $name = 'guest'). Put optional parameters last.

A function returns one value. To return several, return an array or, better, a small object. Without a return, a function gives null; the void return type makes that explicit.

Nullable types are written ?string. Since 8.0 the constructor promotion shorthand lets you declare and assign properties directly in the constructor's parameter list.

Practice. Write a function that returns a value object instead of an array with magic keys, and use a default parameter.

Named Arguments Recommended

Named arguments (PHP 8) let you pass values by parameter name, in any order, and skip optional ones:

function paginate(int $page = 1, int $perPage = 20, bool $withTotal = false) {}
paginate(perPage: 50, withTotal: true);

They make boolean flags readable and combine well with long constructors. The cost is that parameter names become part of a public API: renaming a parameter in a library can break callers who used the name.

You cannot mix a positional argument after a named one. Many core functions accept named arguments too, such as htmlspecialchars($s, double_encode: false).

Practice. Refactor a call that has three unlabelled boolean arguments to use named arguments.

Variadic Functions Recommended

A variadic parameter collects any number of trailing arguments into an array: function total(int ...$amounts): int { return array_sum($amounts); }. You can type it, so every element must be an integer.

The same three dots work in reverse as the spread operator: total(...$list) unpacks an array into arguments, and with string keys it supplies named arguments. Spreading arrays inside array literals merges them, and string keys are allowed from PHP 8.1.

The older func_get_args() function does the same job less clearly and is only seen in legacy code.

Practice. Write a function that accepts any number of strings and returns them joined, then call it with an unpacked array.

Type Declarations Core

Type declarations document intent and let PHP catch mistakes. You can type parameters, return values and properties with scalar types, class names, array, callable, iterable, mixed, self, static and void. Union types (int|string), intersection types and nullable types (?int) cover more cases, and never marks functions that always throw or exit.

Without strict mode, PHP coerces '5' to 5 for an int parameter. Put declare(strict_types=1); first in each file to disable that for calls made from the file.

Types do not replace validation. They check the shape of the data inside your code; user input still needs checking at the edge. Static analysers such as PHPStan rely on types to find bugs without running the code.

Practice. Add full types to a legacy function and run it with strict_types on to discover hidden coercions.

Anonymous Functions, Arrow Functions and Callbacks Core

An anonymous function (closure) is a function value: $double = function (int $n): int { return $n * 2; };. It can capture variables with use. An arrow function is a short single-expression form that captures the outer scope by value: fn($n) => $n * 2.

A callback is any callable passed to another function: a closure, a function name string, an [$object, 'method'] pair or, since 8.1, first-class callable syntax such as strlen(...).

$names = array_map(fn(User $u) => $u->name, $users);
usort($users, fn($a, $b) => $a->age <=> $b->age);

Use callbacks to describe what to do with each item and let the array functions handle the loop.

Practice. Sort a list of products by price then name using usort, then filter and map the same list with arrow functions.

Stage 4 Object-Oriented PHP

Intermediate2–3 weeks6 topics

Goal. Model a small domain with classes, interfaces and traits, and explain when to use each.

OOP Fundamentals Core

Object-oriented programming groups data and the behaviour that works on it into objects. The four ideas interviewers ask about are encapsulation (hide internals behind methods), inheritance (reuse a parent's behaviour), polymorphism (treat different types through one interface) and abstraction (expose what matters, hide the rest).

In PHP, a class is a blueprint and an object is an instance made with new. Objects are passed around as handles: two variables can point at the same object, and clone makes a shallow copy.

Good OOP is about small objects with clear responsibilities, not about wrapping every function in a class. Software Design and Architecture Roadmap goes deeper on design principles.

Practice. Describe a shopping basket as objects on paper first: list the classes, their data and their methods.

Classes and Objects, Properties and Methods Core

final class Money
{
    public function __construct(
        public readonly int $amount,
        public readonly string $currency,
    ) {}

    public function add(Money $other): self
    {
        return new self($this->amount + $other->amount, $this->currency);
    }
}

Properties hold state; methods hold behaviour; $this refers to the current object. The constructor sets the object up, and the destructor __destruct runs when the last reference disappears, which is rarely needed. Typed and readonly properties (8.1) catch errors early and make value objects easy.

Prefer constructors that leave an object fully valid. An object that needs three setter calls before it works is a bug waiting to happen.

Practice. Build an immutable Money class with an add method that rejects mixed currencies.

Access Specifiers Core

Visibility controls who may touch a property or method:

  • public: anywhere.
  • protected: the class and its subclasses.
  • private: only the declaring class.

Default to private and widen only when you must. Public properties are acceptable on simple value objects, especially with readonly, but a public mutable property lets any code break your invariants.

Marking a class or method final stops it being extended or overridden. Many teams make classes final by default and remove it only for a reason, because inheritance couples code tightly.

Practice. Make every property in one of your classes private and see which callers break and why.

Static Methods and Properties Recommended

A static member belongs to the class, not to an instance: Config::get('x'), self::$count. Static methods are fine for pure helpers and named constructors such as Money::fromString().

Static properties are global state in disguise. They persist for the whole request, are shared by every caller and make tests depend on order. Singletons and static service locators have the same issue.

self refers to the class where the code is written; static uses late static binding and refers to the class that was actually called, which matters when a subclass inherits a static factory.

Practice. Write a static named constructor, then a test showing why a static cache makes two tests interfere.

Inheritance and Abstract Classes Core

class Admin extends User gives Admin everything User has, and it can override methods and call the parent with parent::method(). PHP has single inheritance: a class has one parent.

An abstract class cannot be instantiated and may declare abstract methods that subclasses must implement. It suits a family sharing real code, such as a base report class with a fixed render() flow and one abstract rows() step.

Inheritance expresses "is a". When you only want to reuse code, composition is often better: hold another object and call it. The saying "favour composition over inheritance" is a regular interview prompt.

Practice. Create an abstract Report class with a template method and two subclasses, then redo one using composition.

Interfaces and Polymorphism Core

An interface lists method signatures that a class promises to provide, with no implementation. A class can implement many interfaces, which is how PHP handles multiple type relationships.

interface Notifier { public function send(string $to, string $text): void; }
final class SmsNotifier implements Notifier { /* ... */ }
final class EmailNotifier implements Notifier { /* ... */ }

Polymorphism means a function that asks for a Notifier works with any implementation. This is the basis of dependency injection and testing: in a test you pass a fake notifier. Type to the interface, construct the concrete class in one place.

Practice. Write a Notifier interface with two implementations and a test double that records messages.

Stage 5 Advanced Language Features

Intermediate2 weeks5 topics

Goal. Organise code in namespaces, use traits and magic methods sparingly and handle errors with exceptions.

Traits Recommended

A trait is a bundle of methods and properties copied into a class with use. It gives horizontal code reuse in a language with single inheritance, for example a HasTimestamps trait shared by unrelated models.

Conflicts between traits are resolved with insteadof and as. Traits can have abstract and static members.

Use them for small, self-contained helpers. Overuse hides dependencies, because the class silently relies on whatever the trait expects. A trait cannot be type-hinted, so pair it with an interface when callers need a type.

Practice. Extract a shared logging snippet from two classes into a trait and add an interface for it.

Magic Methods Recommended

Methods whose names start with two underscores are called by the engine at special moments:

  • __construct and __destruct: creation and cleanup.
  • __get, __set, __isset: access to inaccessible properties.
  • __call and __callStatic: calls to missing methods.
  • __toString: object to string conversion.
  • __invoke: calling the object like a function.
  • __clone: adjust a copy.

They power ORMs and fluent APIs, but they defeat static analysis and autocomplete, and errors surface late. Use __toString, __invoke and __clone freely; be wary of __get, __set and __call.

Practice. Create a class using __invoke as a callback and __toString for logging, and note what an IDE can and cannot infer.

Namespaces and Autoloading Core

Namespaces prevent name clashes and give classes a hierarchy: namespace App\Billing; at the top of a file, then use App\Billing\Invoice; where needed. By convention one class lives in one file and the namespace matches the folder.

Autoloading means PHP loads a class file the first time the class is used. spl_autoload_register is the mechanism, and the PSR-4 standard maps a namespace prefix to a directory. Composer generates this for you, so you only declare the mapping in composer.json:

"autoload": { "psr-4": { "App\\": "src/" } }

After editing the mapping, run composer dump-autoload.

Practice. Move three classes into src/ under a namespace and load them with a PSR-4 mapping instead of require.

Enums, Readonly and Modern Class Features Recommended

Enums (8.1) define a closed set of values. A backed enum has a scalar value, which makes storing and parsing easy:

enum Status: string {
    case Draft = 'draft';
    case Live = 'live';
}
$s = Status::from('live');   // throws on bad input
$t = Status::tryFrom('x');   // null on bad input

Enums can have methods and implement interfaces. Readonly properties can be set once, from inside the class. Other modern tools are attributes (structured metadata that frameworks read), first-class callable syntax and constructor promotion. Together they remove much old boilerplate.

Practice. Replace status strings in a small app with an enum and add a method that returns a display label.

Exceptions and Error Handling Core

Modern PHP reports most problems by throwing. Throwable is the root, with Exception for application errors and Error for engine errors such as TypeError. Use try, catch and finally, catch specific classes first, and create your own exception types for domain failures.

try {
    $order = $repo->find($id);
} catch (OrderNotFound $e) {
    http_response_code(404);
}

Do not catch everything and ignore it. Log with context, show users a safe message and never display stack traces in production (display_errors off, log_errors on). Register a global handler with set_exception_handler as a last line of defence.

Practice. Define a domain exception, throw it from a repository method and handle it at the edge with a proper HTTP status.

Stage 6 PHP on the Web

Intermediate2–3 weeks6 topics

Goal. Handle requests, forms, sessions, files and data formats the way a real web application does.

HTTP Methods and Superglobals Core

HTTP methods express intent: GET reads and must not change data, POST creates or submits, PUT and PATCH update, DELETE removes. HTML forms only send GET and POST; APIs and JavaScript use all of them.

PHP exposes request data through superglobals. $_GET holds query string values, $_POST holds form body fields, $_REQUEST merges them with cookies (and its mix is why most developers avoid it), $_SERVER holds headers and server facts such as REQUEST_METHOD, and $_FILES, $_COOKIE and $_SESSION do what their names say.

Everything in these arrays is untrusted text. Read with a default ($_GET['q'] ?? ''), validate, then use. For JSON bodies, read php://input and json_decode it.

Practice. Write a script that responds differently to GET and POST and returns 405 for other methods.

Form Processing Core

The cycle is: show a form, receive the POST, validate, act, then redirect. Redirecting after a successful POST (Post/Redirect/Get) stops a browser refresh from resubmitting.

Validation should return per-field messages and keep what the user typed so they can fix it. Escape every value you print back with htmlspecialchars($v, ENT_QUOTES, 'UTF-8'). Add a CSRF token to every state-changing form.

Server-side validation is mandatory; HTML attributes such as required are a convenience only, because anyone can send a request without a browser.

Practice. Build a contact form that validates name, email and message, redisplays errors and redirects on success.

Cookies, Sessions and State Management Core

HTTP is stateless, so a site remembers users with cookies, which the browser sends with each request. A session stores data on the server under an ID held in a cookie: session_start(), then read and write $_SESSION.

Secure the session cookie with the HttpOnly, Secure and SameSite flags, call session_regenerate_id(true) after login to prevent fixation, and set sensible lifetimes. Store only an identifier in the cookie, never trusted data such as a role.

State can also live in the database, in a cache such as Redis (needed when several servers share sessions), or in signed tokens. Pick based on who must be able to read or revoke it.

Practice. Build a login flow that stores the user ID in a session, regenerates the ID, and logs out cleanly.

File Uploads Recommended

Uploads arrive in $_FILES with a temporary path, a client-supplied name, a size and an error code. Move the file with move_uploaded_file, which also checks it really came from an upload.

Never trust the client name or reported type. Check the error code, enforce a size limit (and match upload_max_filesize and post_max_size in php.ini), detect the real type with finfo, generate your own file name, and store uploads outside the web root or in object storage. Serving user-uploaded .php files from a public folder is a classic remote code execution hole.

Practice. Build an image upload that accepts only JPEG and PNG, limits size and saves under a random name.

Reading and Writing Files Core

For small files, file_get_contents and file_put_contents are enough. For large files, open a handle with fopen, read with fgets or fread in a loop, and fclose when done. SplFileObject offers an object interface, and file() returns lines as an array.

file_put_contents($path, $line . PHP_EOL, FILE_APPEND | LOCK_EX);

LOCK_EX prevents two requests writing at the same moment. Check return values; these functions return false on failure. Validate any path that includes user input, with basename() and realpath(), to block directory traversal such as ../../.

Practice. Write an append-only log function with locking, and a reader that tails the last ten lines efficiently.

CSV, JSON and XML Processing Core

CSV: use fgetcsv and fputcsv, which handle quotes and delimiters properly. Splitting on commas by hand fails the first time a field contains one.

JSON: json_encode and json_decode. Pass JSON_THROW_ON_ERROR so failures throw instead of returning null, and use true as the second argument of json_decode for arrays rather than objects.

XML: SimpleXML is the quick option, DOMDocument gives full control and XMLReader streams large files. When parsing XML from untrusted sources, avoid loading external entities, which was a source of file disclosure bugs in older versions.

Practice. Convert a CSV of products to JSON with correct number types, then parse a small XML feed into an array.

Stage 7 Databases and Dependencies

Intermediate2–3 weeks7 topics

Goal. Talk to a database safely, manage packages with Composer and structure services with dependency injection.

Database Connectivity with MySQLi and PDO Core

PHP has two main database APIs. MySQLi works only with MySQL and MariaDB and offers procedural and object styles. PDO is a common interface for many databases, so switching from MySQL to PostgreSQL changes the connection string and little else. Most new code uses PDO.

$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();

Always use prepared statements with bound values. Set the exception error mode and the charset (utf8mb4 for MySQL). See SQL Roadmap for query skills.

Practice. Write a small repository class with PDO that finds, inserts and updates users using only prepared statements.

Database Transactions Core

A transaction groups statements so that they all succeed or none do. Use it whenever several writes must stay consistent, such as creating an order and reducing stock.

$pdo->beginTransaction();
try {
    // several statements
    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    throw $e;
}

Keep transactions short, because they hold locks. Know the term isolation level and what a deadlock is: two transactions each waiting for the other. A common fix is to take locks in a consistent order and retry on a deadlock error. Note that MySQL's DDL statements commit implicitly.

Practice. Write a money transfer between two accounts that rolls back when the balance would go negative.

Database Migrations and ORMs Recommended

A migration is a versioned script that changes the schema, so every environment can be brought to the same state with one command. Tools such as Phinx, Doctrine Migrations and the Laravel migration system record which migrations have run and can roll back.

An object-relational mapper (ORM) maps tables to objects. Doctrine uses the data-mapper style, where entities are plain classes; Eloquent in Laravel Roadmap uses active record, where the model saves itself. ORMs save effort on routine queries but can hide the N+1 query problem, where one list triggers one extra query per row. Learn to read the generated SQL and eager-load related data.

Practice. Create a migration that adds a table and an index, run it, roll it back, and list the SQL an ORM generates for a list page.

Composer and Packagist Core

Composer is PHP's dependency manager. Packagist is the main public repository it reads from. You declare requirements in composer.json, run composer install, and Composer downloads packages into vendor/ and writes a composer.lock file with the exact versions.

Commit the lock file for applications so every deploy installs identical versions; libraries usually do not rely on it. Version constraints such as ^2.1 allow compatible updates. composer require, composer update and composer audit (which checks for known vulnerable versions) are the commands to know.

Never edit vendor/ by hand and never run composer update blindly on production. Composer also provides the autoloader and scripts hooks.

Practice. Start a project with Composer, add a package and a dev dependency, then run composer audit and explain the lock file.

PSR Standards and PHP-FIG Recommended

PHP-FIG is a group of projects that publish interoperability recommendations called PSRs. They matter because they let frameworks and libraries work together.

  • PSR-1 and PSR-12 (and its successor PER Coding Style): coding style.
  • PSR-4: autoloading.
  • PSR-3: logger interface.
  • PSR-7 and PSR-17: HTTP messages and factories; PSR-15: middleware; PSR-18: HTTP client.
  • PSR-11: container interface; PSR-6 and PSR-16: caching.

Type against the interface (a PSR-3 logger, say) and you can swap the implementation without touching your code.

Practice. Replace a hand-written logger dependency in a class with the PSR-3 interface and plug in Monolog.

Dependency Injection Core

A class should receive the things it needs instead of creating or fetching them itself. Constructor injection is the standard form:

final class Checkout
{
    public function __construct(
        private PaymentGateway $gateway,
        private LoggerInterface $logger,
    ) {}
}

This makes dependencies visible and lets tests pass fakes. A dependency injection container (PHP-DI, the Symfony container or Laravel's) builds the object graph, often through autowiring from type declarations. The container belongs at the application edge; passing the container into classes so they pull what they want (service location) hides dependencies again.

Practice. Write Checkout with injected interfaces, then build it by hand in a composition file without any container.

Configuration Files and Environment Variables Core

Code stays the same between environments; configuration changes. Database passwords, API keys and debug flags belong in environment variables, read with getenv() or $_ENV, not in committed source files. During development, a .env file loaded by a library such as vlucas/phpdotenv is common. Never commit it, and keep it outside the public document root.

Group non-secret settings in config files that return arrays. Validate required values at start-up so a missing variable fails fast with a clear message. Use separate values for development, test and production, and rotate any secret that has ever been committed.

Practice. Load database settings from environment variables, fail clearly when one is missing, and add .env to .gitignore.

Stage 8 Security

Intermediate2 weeks6 topics

Goal. Recognise and prevent the common web attacks that PHP applications face.

Input Validation and Sanitization Core

Validation checks that input has the expected shape and rejects it otherwise: is this an integer between 1 and 100, an email, one of the allowed values? Sanitization changes input to make it safe for a specific use, such as stripping tags.

Prefer validation with an allow-list over cleaning. filter_var($v, FILTER_VALIDATE_EMAIL) and FILTER_VALIDATE_INT with options cover common cases. Check length and type, and normalise whitespace.

Validation is not escaping. The safe treatment depends on where the value goes: bound parameters for SQL, htmlspecialchars for HTML, escapeshellarg for shell. Do the right one at the point of use.

Practice. Write a validator that returns a list of errors for a registration form using filter_var and allow-lists.

SQL Injection Core

SQL injection happens when user input becomes part of the query text. If you build "... WHERE name = '$name'" and a visitor sends ' OR '1'='1, they change the query's meaning, and worse inputs can read or destroy data.

The fix is prepared statements, which send the query and the values separately so values can never become code. Escaping by hand is fragile. Identifiers and keywords such as column names cannot be bound, so check them against an allow-list.

Also give the application's database user only the permissions it needs, so that an injection bug has limited reach.

Practice. Break a deliberately vulnerable login query with an injection string, then fix it with prepared statements.

XSS Prevention Core

Cross-site scripting runs an attacker's JavaScript in other users' browsers, typically because stored or reflected input was printed without escaping. It can steal sessions, perform actions as the user or rewrite the page.

Escape on output for the correct context. In HTML text and attributes use htmlspecialchars($v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'). In JavaScript, pass data as JSON with json_encode and the hex flags, or in a data attribute. Template engines such as Twig and Blade escape by default; learn how to find the raw output syntax and treat it as a warning sign.

A Content-Security-Policy header and HttpOnly cookies reduce the damage but do not replace escaping.

Practice. Create a comment page that is vulnerable to stored XSS, then fix it and add a Content-Security-Policy header.

CSRF Protection Core

Cross-site request forgery tricks a logged-in user's browser into sending a request, such as changing an email address, from another site. The browser attaches cookies automatically, so the server thinks the user did it.

Defences: include a random per-session token in each state-changing form and check it with hash_equals; set SameSite=Lax or Strict on cookies; and never change state with GET. APIs that use a bearer token in a header rather than a cookie are not exposed in the same way.

Frameworks usually provide this. You should still be able to explain how it works and build the check by hand.

Practice. Add a CSRF token to a form, verify it with hash_equals and show that a forged request is rejected.

Password Hashing and Authentication Mechanisms Core

Never store passwords in plain text or with fast hashes like MD5 or SHA-1. Use password_hash($password, PASSWORD_DEFAULT) (or PASSWORD_ARGON2ID when available), which picks a strong algorithm, salts automatically and produces a string you store whole. Check with password_verify, and call password_needs_rehash on login to upgrade old hashes.

Common authentication mechanisms are cookie sessions, API tokens, JSON Web Tokens and OAuth 2.0 or OpenID Connect for logging in through a provider. Add rate limiting, generic error messages ("invalid email or password"), and multi-factor authentication where the risk justifies it. See API Design Roadmap for API authentication choices.

Practice. Implement register and login with password_hash and verify, including rehash on login.

File Permissions and Executing System Commands Recommended

Run PHP as an unprivileged user. Directories typically need 0755 and files 0644; only the folders the app writes to (cache, uploads) should be writable by the PHP user, and never 0777. Keep configuration and uploads out of the document root.

exec, shell_exec, system and passthru run operating-system commands. If any part comes from a user, you risk command injection. Prefer a PHP library over a shell tool, pass arguments through escapeshellarg, avoid shell metacharacters entirely with proc_open and an argument array, and consider turning the functions off with disable_functions on shared servers.

Practice. Call an image tool from PHP with proc_open and an argument array, and show that a hostile filename is harmless.

Stage 9 Testing, Quality and Debugging

Intermediate2 weeks4 topics

Goal. Test code automatically, let tools find bugs and style problems, and debug with a real debugger.

Testing with PHPUnit and Pest Core

PHPUnit is the standard test framework: a test class extends TestCase, each test* method (or one with the #[Test] attribute) makes assertions, and phpunit runs them. Pest, built on PHPUnit, offers a terser syntax with it() and expect().

public function test_total_adds_vat(): void
{
    $this->assertSame(120, (new Price(100))->withVat(0.2)->amount);
}

Write unit tests for logic without I/O, integration tests for database code, and a few end-to-end tests for key flows. Use data providers for many inputs, and fakes or mocks for external services. Aim for fast, independent tests that run on every push in CI.

Practice. Test a pricing class with a data provider covering edge cases, and run the same tests in Pest.

Static Analysis: PHPStan, Psalm and Phan Recommended

Static analysis reads your code without running it and reports type errors, undefined methods, dead code and impossible conditions. PHPStan and Psalm are the most used; Phan is another option. You choose a strictness level (PHPStan numbers them from 0 upwards) and raise it over time.

A baseline file records existing errors so a legacy project can adopt the tool and only block new problems. Generic annotations in doc comments (@param list<int> $ids) tell the tool what native types cannot. Run it in CI with the tests; it catches many bugs a unit test would miss.

Practice. Run PHPStan at level 5 on an old project, create a baseline and fix the five most serious findings.

Coding Style Tools: PHP CodeSniffer and PHP CS Fixer Recommended

Style tools make formatting a non-issue in code review. PHP CodeSniffer (phpcs) reports violations against a ruleset such as PSR-12 and fixes some with phpcbf. PHP CS Fixer rewrites the code according to a configurable rule set and is often used to enforce modern idioms too.

Pick one, commit its configuration, run it in a pre-commit hook or in CI, and stop arguing about braces. Style rules are about consistency, not correctness; do not let them replace tests and static analysis.

Practice. Add PHP CS Fixer with the PSR-12 ruleset to a project and run it in a CI job that fails on differences.

Debugging with Xdebug Recommended

Xdebug is a PHP extension that adds step debugging, stack traces, code coverage and profiling. With an editor such as PhpStorm or VS Code you set a breakpoint, trigger the request, then step through lines and inspect variables, which beats scattering var_dump calls.

Enable it only in development, because it slows PHP noticeably. Set the mode in configuration (xdebug.mode=debug,coverage) and point the client port at your editor. Zend Debugger is an older alternative that you may find in legacy PhpStorm setups. Also learn to read a stack trace from the bottom upwards: it shows how execution reached the failing line.

Practice. Debug a failing function with a breakpoint and a watch expression, and find the wrong value without var_dump.

Stage 10 Performance, Production and the Wider Ecosystem

Advanced3 weeks6 topics

Goal. Run PHP efficiently in production, call other services, and know the frameworks and tools around the language.

PHP-FPM and Configuration Tuning Core

PHP-FPM (FastCGI Process Manager) keeps a pool of PHP worker processes ready and talks to Nginx or Apache over a socket. The key settings are the process manager mode (static, dynamic or ondemand) and pm.max_children, which caps concurrent requests per pool.

Set max_children from memory: divide the RAM you can spare by the typical memory per worker. Too high and the server swaps; too low and requests queue. Other php.ini settings that matter are memory_limit, max_execution_time, upload_max_filesize, error_reporting and display_errors. Keep a separate production ini, with errors logged and not shown.

Practice. Measure memory per PHP-FPM worker under load and calculate a sensible pm.max_children.

Opcode Caching and Memory Management Core

Without caching, PHP would parse and compile each file on every request. OPcache stores the compiled opcodes in shared memory so later requests skip that work, often giving a large speed-up for free. Enable it in production, size opcache.memory_consumption to hold your code, and decide on revalidation: in production with immutable deploys you can switch timestamp checks off and reset the cache on deploy.

Memory management is mostly automatic: reference counting frees most values immediately, and a cycle collector handles circular references. Long-running scripts (queue workers) can still leak, so watch memory_get_usage(), free large arrays, use generators, and restart workers periodically.

Practice. Compare request times with OPcache off and on, then print memory use while processing a large file with and without a generator.

Caching Strategies and Connection Pooling Recommended

Cache the expensive things: query results, rendered fragments, API responses. Choices include APCu (per-server memory), Redis or Memcached (shared across servers) and HTTP caching with Cache-Control and ETag headers. The PSR-6 and PSR-16 interfaces let you swap stores. Decide how entries expire, and plan invalidation, which is the hard part: a stale price is a bug.

PHP normally starts a fresh process per request, so database connections are not pooled in the language. Persistent connections (PDO::ATTR_PERSISTENT) reuse them within a worker, and a proxy such as ProxySQL or PgBouncer pools across workers. Watch the database's maximum connections against your worker count. See Redis Roadmap for the cache store.

Practice. Cache a slow query result in Redis with a five-minute expiry and prove the second request is faster.

Profiling and Performance Optimization Recommended

Measure before optimising. A profiler such as Xdebug's profiler, Blackfire or XHProf-style tools shows which functions take the time. In most web applications the biggest wins are fewer database queries (fix N+1 problems, add indexes), caching, avoiding repeated work in loops and sending less data.

Micro-optimisations such as single versus double quotes make no meaningful difference. Newer PHP versions are faster, so upgrading is itself an optimisation. Use microtime(true) for rough timings and application performance monitoring in production. Always compare the same scenario before and after a change.

Practice. Profile a slow page, identify the top three costs and fix the largest one, recording before and after timings.

HTTP Clients: cURL and Guzzle Recommended

To call another service from PHP use the cURL extension or Guzzle, a client library that wraps it with a friendlier API, async requests and middleware. Libraries following PSR-18 (and the built-in Symfony HttpClient) are alternatives.

$client = new GuzzleHttp\Client(['timeout' => 5]);
$res = $client->get('api.example.test/items', ['query' => ['page' => 1]]);
$data = json_decode((string) $res->getBody(), true, flags: JSON_THROW_ON_ERROR);

Always set timeouts, check status codes, handle failures and retry with backoff for safe requests. Never disable TLS certificate verification to silence an error.

Practice. Fetch JSON from a public API with Guzzle, handle a timeout and a 500 response, and log both.

Frameworks: Laravel, Symfony and Yii Recommended

Frameworks supply routing, dependency injection, an ORM, validation, templating, queues and security defaults. Laravel is the most popular and favours convention and speed of development (see Laravel Roadmap). Symfony is a set of decoupled components plus a full-stack framework, and many other projects (including Laravel and Drupal) use its components. Yii is a high-performance framework with a generator tool called Gii.

Learn plain PHP first, then one framework well. Interviewers ask about the request lifecycle, middleware, the service container and how the ORM avoids N+1 problems, and those answers carry over between frameworks.

Practice. Build the same small CRUD page in a framework and note which parts of it you already knew from plain PHP.

Projects to build

Build these in order. Each one should end up in a public repository with a short README that explains your decisions.

  1. Command line expense trackerBeginner

    Write a CLI script that adds, lists and totals expenses stored in a JSON file, with arguments for category and date. Keep the logic in functions and give each a type declaration.

    Functions · Arrays · File handling · JSON

  2. Guestbook with validationBeginner

    Build a page where visitors post messages through a form. Validate input, escape output, save to a database with PDO and redirect after posting.

    Forms · Validation · PDO · Escaping output

  3. Mini MVC frameworkIntermediate

    Create a front controller, a router that maps paths to controller classes, a small dependency injection container and a template renderer. Autoload everything with PSR-4.

    Namespaces · Interfaces · Dependency injection · Composer

  4. Authenticated notes appIntermediate

    Add registration, login, sessions and per-user notes with CSRF protection and password hashing. Include a file attachment upload with type and size checks.

    Sessions · Password hashing · CSRF · File uploads

  5. JSON API with testsAdvanced

    Build a REST-style API for a bookshop with pagination, validation errors and token authentication. Cover it with PHPUnit tests, run PHPStan at a high level and add a cache for the list endpoint.

    HTTP · PHPUnit · Static analysis · Caching · Security

Interview questions

Try to answer each question out loud before you open the answer.

What is the difference between == and === in PHP?Junior

== compares after type juggling, so '1' == 1 and null == false are true. === compares value and type, so both are false. I use === by default because loose comparison hides bugs, and the rules for comparing strings and numbers changed in PHP 8. I only use == when I really want conversion, and I say so in a comment.

Explain include, include_once, require and require_once.Junior

All four load and run another file. require raises a fatal error if the file is missing, while include raises a warning and continues. The _once versions skip the file if it was already loaded, which avoids redefinition errors. Modern code uses Composer's autoloader and requires only vendor/autoload.php.

How do sessions work in PHP, and how do you secure them?Junior

session_start() creates or resumes a session identified by an ID in a cookie, and the data is kept on the server, by default in files. To secure it, set the cookie flags HttpOnly, Secure and SameSite, regenerate the ID on login, keep lifetimes short, and use a shared store such as Redis when several servers handle requests.

What are prepared statements and why do they prevent SQL injection?Junior

A prepared statement sends the SQL with placeholders to the database first, then sends the values separately. The database has already parsed the query structure, so a value can never change it. That makes injection impossible for bound values. I still allow-list identifiers such as column names, which cannot be bound.

What is the difference between an abstract class and an interface?Junior

An interface describes a contract with no implementation, and a class can implement many. An abstract class can hold state and shared code and leaves some methods for subclasses, but a class can extend only one. I use an interface to define what collaborators can do, and an abstract class when subclasses share real behaviour.

How does Composer autoloading work?Mid

Composer generates vendor/autoload.php, which registers an autoloader with PHP. When code uses a class that is not loaded yet, the autoloader maps its namespace to a file by the rules in composer.json, usually PSR-4, and requires it. In production, composer dump-autoload -o builds a class map so lookups avoid disk checks.

How do you prevent XSS and CSRF?Mid

For XSS, escape output for its context, with htmlspecialchars for HTML, use auto-escaping templates and set a Content-Security-Policy. For CSRF, put a random token in each state-changing form and compare it with hash_equals, set SameSite on cookies and never change data on GET. They are different problems: XSS runs hostile script on my site, CSRF forges requests from a trusted browser.

What is the N+1 query problem and how do you fix it?Mid

It happens when code loads a list with one query and then runs one more query for each item, such as loading authors inside a loop over posts. Fix it by loading related data in bulk: a join, a WHERE id IN (...) query, or the ORM's eager loading. I spot it by counting queries in a debug toolbar or log.

How does PHP handle memory, and what would you check for a worker that keeps growing?Senior

Reference counting frees most values when the last reference goes, and a cycle collector handles cycles. In a long-running worker I check for growing static arrays, caches without limits, unreleased large results and event listeners that keep objects alive. I log memory_get_usage() per job, process in chunks with generators and restart workers after a number of jobs.

How would you speed up a slow PHP application?Senior

I would measure first: use a profiler and query logs to find where time goes. Then I fix the biggest cost, usually database queries (indexes, N+1), then add caching, enable OPcache, tune PHP-FPM and upgrade PHP. I compare before and after under the same load and keep monitoring so regressions are visible.

How do you structure a PHP application without a framework?Senior

A single front controller (public/index.php) receives all requests. A router maps them to controllers, services hold business logic behind interfaces, repositories handle persistence, and a container wires them together. Everything is namespaced and autoloaded with PSR-4. I keep configuration in environment variables and put only public/ in the web root.

How do you secure file uploads?Senior

I check the upload error code, limit the size, detect the real type with finfo rather than trusting the client, allow only specific types, generate a random file name and store files outside the web root or in object storage. I never execute uploaded files, and I scan them if risk is high.

Common mistakes

  • Printing user data without escaping it: always pass output through htmlspecialchars or a template that escapes automatically.
  • Building SQL by concatenating variables: use prepared statements with bound values every time.
  • Using == and trusting loose comparison: use === and enable strict_types.
  • Leaving display_errors on in production: log errors and show a generic page instead.
  • Pointing the web root at the project folder: serve only the public directory so source and .env files stay private.
  • Storing passwords with MD5 or SHA-1: use password_hash and password_verify.
  • Putting business logic inside templates and controllers: move it into small classes you can test.
  • Copying packages into the project by hand: use Composer and commit the lock file.
  • Learning a framework before the language: spend time on plain PHP so the framework stops being magic.
  • Running an unsupported PHP version: check the support table and upgrade before security fixes stop.

Ready-for-interview checklist

  • I can explain how a PHP request is handled from the web server to the response
  • I can write functions with type declarations, default values and named arguments
  • I can use arrays, array functions and closures to transform data
  • I can design classes with interfaces, inheritance, traits and enums, and say when to use each
  • I can organise code with namespaces and a PSR-4 autoloader
  • I can build a form flow with validation, sessions and a Post/Redirect/Get redirect
  • I can query a database with PDO prepared statements and use a transaction
  • I can manage dependencies with Composer and explain the lock file
  • I can defend against SQL injection, XSS and CSRF and hash passwords correctly
  • I can write PHPUnit or Pest tests and run static analysis
  • I can describe how PHP-FPM, OPcache and caching affect performance
  • I can debug with Xdebug and read a stack trace

Related roadmaps

  • Laravel RoadmapRouting, Eloquent, queues, testing and deployment.
  • WordPress RoadmapThemes, plugins, blocks, hooks, security and performance.
  • SQL RoadmapQueries, joins, window functions, indexes and transactions.
  • API Design RoadmapREST, gRPC, GraphQL, versioning, auth, pagination and rate limits.
  • Redis RoadmapData types, caching patterns, persistence, clustering and streams.

FAQ

Is PHP still worth learning?

Yes. PHP runs a very large number of existing sites and applications, and there is steady demand for developers who can maintain and extend them. Modern PHP with a framework is a productive way to build web backends. If you want the widest range of employers, pair it with JavaScript and SQL.

How long does it take to learn PHP?

Most people can write useful scripts after three to four weeks and build a small database-backed site within two to three months. Interview readiness, including OOP, security, testing and Composer, usually takes three to four months at about eight hours a week.

Should I learn PHP or a framework like Laravel first?

Learn core PHP first: types, arrays, OOP, namespaces, PDO and Composer. A framework builds on these and uses them constantly, so you will understand what it does for you. Then move to Laravel Roadmap or Symfony.

Which PHP version should I learn?

Learn the latest stable release of PHP 8, and read the support table when choosing for production. Be aware that many existing projects run older 7.x or early 8.x versions, so know the main differences, such as missing enums or match in older code.

Is PHP slow?

Current PHP is fast for typical web workloads, especially with OPcache enabled. Most slow PHP applications are slow because of database queries and missing caching, not the language itself. Profile before blaming the runtime.

Practise while you learn.Solve interview problems in the browser, with hints and a timer.
CodingSQLSystem design
Next Post Previous Post
No Comment
Add Comment
comment url