PHP Tutorial for Beginners
Learn PHP step by step, from your first echo to forms, sessions, MySQL databases, object-oriented PHP, web security and a REST API, with reference guides for when you need more depth.
Browse all 86 lessons by stage
- Lessons
- 86
- Code examples
- 162
- Exercises
- 186
- Quiz questions
- 247
PHP course at a glance
Who it's for
Beginners building dynamic websites, WordPress and Laravel learners, and front-end developers moving to the back end.
Prerequisites
Basic HTML helps, because PHP usually produces it. No programming experience is needed.
What you need
PHP 8.1 or newer, a code editor such as VS Code and a terminal. SQLite covers the database chapters without a server.
How long it takes
Two to three months for the 25 core chapters at five hours a week; read references as needed.
PHP roadmap: beginner to advanced
Work through the 25 core chapters in the first three stages in order, then use the reference stages to go deeper. Each reference lesson links to its prerequisite and includes examples, practice and a quiz.
Beginner
Your first PHP page, variables, strings, decisions, loops, arrays and functions.
- 1IntroductionWhat PHP is, how it builds web pages on the server, and how to write and run your first script.
- 2Variables & StringsStore values in $variables, learn PHP's data types, and build text with concatenation and interpolation.
- 3String FunctionsWork with text in PHP: length, changing case, searching, replacing, trimming, splitting and joining, formatting with sprintf and number_format, and handling UTF-8 safely.
- 4if / else / matchMake decisions with comparison operators, if, elseif, else, logical operators and match.
- 5LoopsRepeat code with for, while and foreach loops, and use loops to build HTML lists and tables.
- 6ArraysStore lists and labelled data in indexed and associative arrays, and use PHP's array functions.
Show all 8 lessonsShow fewer
Intermediate
Includes, forms, validation, sessions, dates, regex, files, JSON and PDO: building interactive, data-driven pages.
- 9include & requireSplit a site into reusable files with include, require and their _once versions, and build a simple page layout.
- 10Forms (GET & POST)Receive form data with $_GET and $_POST, choose the right method, keep forms sticky and redirect after a successful submission.
- 11Form ValidationValidate required fields, emails, numbers and lengths on the server, collect error messages and protect forms with CSRF tokens.
- 12Sessions & CookiesRemember information between page loads with sessions and cookies, build a simple login and keep both secure.
- 13Dates & TimesShow, calculate and compare dates in PHP with date(), strtotime and the DateTimeImmutable class, including formats, intervals, differences and time zones.
- 14Regular ExpressionsSearch, validate, extract and replace text by pattern with PHP's preg functions: delimiters, character classes, quantifiers, groups and flags.
Show all 9 lessonsShow fewer
- 15Files & UploadsRead and write files with file_get_contents and file_put_contents, process CSV files, work with folders and handle uploads safely.
- 16JSON & APIsConvert PHP arrays to JSON and back, read JSON from APIs and files, and send JSON responses from your own simple API.
- 17Databases (PDO)Connect PHP to MySQL or SQLite with PDO, run queries, use prepared statements to prevent SQL injection and turn rows into HTML.
Advanced
OOP, exceptions, Composer, a CRUD app, secure logins, web security and REST APIs.
- 18Classes & OOPWrite object-oriented PHP: classes, properties and methods, constructor promotion, visibility, static members, inheritance and interfaces.
- 19Interfaces, Traits & EnumsDesign flexible PHP code with abstract classes, interfaces and polymorphism, share methods with traits, and model fixed choices with enums and readonly properties.
- 20Exceptions & ErrorsHandle problems gracefully with try, catch and finally, throw your own exceptions and configure error reporting safely.
- 21Namespaces & ComposerOrganise a PHP project with namespaces, load classes automatically with PSR-4 autoloading, and install third-party packages with Composer.
- 22CRUD AppBuild a complete create, read, update and delete feature with PHP, PDO and MySQL, using prepared statements, validation, safe output and the Post/Redirect/Get pattern.
- 23Login & PasswordsBuild secure registration and login: hashing passwords with password_hash, checking them with password_verify, sessions, protecting pages, logging out and limiting login attempts.
Show all 8 lessonsShow fewer
- 24Web SecurityProtect PHP sites from the most common attacks: cross-site scripting, SQL injection, cross-site request forgery, session hijacking, unsafe uploads and leaked errors.
- 25REST APIBuild a small JSON REST API in plain PHP: routes for each HTTP method, reading JSON request bodies, validation, status codes, error responses and testing with curl.
Fundamentals reference
Companions to variables, decisions and functions. Read the linked foundation lesson before choosing a reference.
- 26Constants and define()Give fixed application values clear names with const, define(), defined() and constant().
- 27Magic constantsUse location-aware constants to build paths, identify methods and diagnose code without hardcoded filenames.
- 28Numbers and mathCalculate with integers and floats, choose rounding rules and recognize precision and conversion pitfalls.
- 29Increment and decrementRead pre-increment and post-increment correctly and keep counters clear in loops and calculations.
- 30Shorthand if and ternaryChoose between full ternary, short ternary and null coalescing without losing valid zero or empty values.
- 31switch versus matchCompare switch statements with PHP 8 match expressions and choose clear, predictable branching.
Show all 10 lessonsShow fewer
- 32Scope and $GLOBALSUnderstand function boundaries, global access, static locals and closure capture before sharing state.
- 33Request superglobalsDistinguish server metadata, mixed request data and environment settings while validating each boundary.
- 34isset, empty and unsetDistinguish missing, null and false-like values, then remove variables or array keys deliberately.
- 35Built-in functionsNavigate PHP function families, read signatures and choose predictable APIs for strings, arrays, dates and data.
Arrays and functions reference
Collection operations, function arguments, types and modern PHP language features.
- 36Indexed and associative arraysModel lists and named records with PHP's ordered-map array type and preserve keys intentionally.
- 37Multidimensional arraysWork with lists of records and nested maps using deliberate lookup, filtering, grouping and aggregation.
- 38Array sorting referenceChoose sorting by key or value, preserve identity and write reliable custom comparison functions.
- 39Callbacks and closuresPass behavior as a value, capture selected context and design small callable-based operations.
- 40Arrow functionsWrite compact single-expression callbacks and understand by-value capture, objects and static closures.
- 41Variadic and named argumentsAccept variable-length inputs, unpack arguments and use PHP 8 named calls with stable parameter contracts.
Show all 10 lessonsShow fewer
- 42Iterables and generatorsAccept arrays or traversable objects and produce values lazily without building an entire result list.
- 43Type declarationsDeclare input and output contracts, understand strict_types and separate language types from business validation.
- 44Null coalescing and nullsafeSupply defaults for missing or null data and traverse optional object relationships without hiding other errors.
- 45Enums and readonlyModel fixed choices with enum cases and protect initialized property bindings with readonly.
OOP reference
Focused explanations of object behaviour after the classes and advanced OOP chapters.
- 46Abstract classesBuild a non-instantiable base class with shared implementation and required methods while keeping inheritance focused.
- 47Class constantsKeep fixed values with their owning class, control access and understand self versus static lookup.
- 48Static methods and propertiesUse class-level operations deliberately and recognize shared mutable state, inheritance and testing trade-offs.
- 49Constructors and destructorsEstablish valid objects at construction and keep important resource cleanup explicit rather than relying on destruction timing.
- 50Traits and conflictsReuse focused methods across classes and resolve competing trait implementations explicitly.
- 51Late static bindingDistinguish the declaring class from the called class and design inherited factories with predictable construction.
Show all 10 lessonsShow fewer
- 52Magic methodsUnderstand automatic object hooks, implement controlled virtual access and prefer explicit interfaces for stable behavior.
- 53Object iterationExpose deliberate collection traversal instead of relying on object properties and choose a fresh iterator policy.
- 54Namespaces and aliasesOrganize class names, import aliases and distinguish name resolution from Composer file loading.
- 55Object cloning and comparisonSeparate shared object references, shallow cloning, custom clone hooks and identity versus value comparison.
Web requests and data reference
Validation, safe files, CSV, XML, browser requests, response headers and mail configuration.
- 56PHP Filters and Validation FiltersLearn filter_var and filter_input, validate integers and emails, handle false safely, and separate validation from output escaping.
- 57Advanced File Handling and File PermissionsHandle PHP files safely with checked paths, stream reads, cooperative locks, atomic replacement, and Linux and Windows permissions.
- 58File Upload Security and MIME-Type ValidationSecure PHP uploads with error and size checks, server MIME detection, generated names, private storage, and controlled downloads.
- 59CSV ProcessingRead and write CSV with fgetcsv and fputcsv, validate headers and rows, set escape explicitly, and protect spreadsheet exports.
- 60XML Processing with SimpleXMLParse XML with PHP SimpleXML, read elements and attributes, handle namespaces, report parsing failures, and avoid unsafe entity options.
- 61XML Processing with DOMUse DOMDocument and DOMXPath to create and edit XML, work with text nodes and namespaces, and handle parse errors safely.
Show all 11 lessonsShow fewer
- 62XML Parsing with ExpatUse PHP's event-based XML parser with element and character handlers, chunked input, final parsing, and precise error reporting.
- 63AJAX with PHPConnect JavaScript fetch to a PHP JSON endpoint, validate requests, handle HTTP errors, protect state changes, and update the page safely.
- 64PHP Live Search with AJAXBuild PHP live search with debounced fetch requests, prepared SQL, bounded results, safe DOM rendering, and protection against stale responses.
- 65HTTP Headers, Redirects and Response CodesUse PHP header and http_response_code for JSON, redirects, downloads, and errors; avoid headers-already-sent and open redirects.
- 66Email Sending and Mail ConfigurationUnderstand PHP mail, SMTP configuration, delivery failures, header safety, queues, and local testing without sending real email.
Database reference
Optional MySQLi alongside the PDO route, plus transactions, errors and pagination.
- 67MySQLi vs. PDOCompare PHP MySQLi and PDO, supported databases, placeholders, fetch APIs, transactions, and practical migration choices.
- 68Connecting PHP to MySQLConnect PHP to MySQL with PDO or optional MySQLi, set utf8mb4, load protected credentials, and diagnose connection failures.
- 69Creating Databases and Tables with PHPRun controlled MySQL schema setup from PHP, choose types and constraints, separate migration privileges, and understand implicit commits.
- 70Insert, Select, Update and Delete with MySQLiPractice optional MySQLi CRUD with prepared values, explicit column lists, safe updates and deletes, and clear affected-row behavior.
- 71Prepared Statements with MySQLiLearn MySQLi prepare, bind_param, execute, bind_result and fetch, including reference binding, dynamic IN values, and identifier limits.
- 72Last Insert ID and Multiple InsertsRead generated IDs with PDO and optional MySQLi, batch inserts safely, understand gaps, and use transactions for related rows.
Show all 10 lessonsShow fewer
- 73Transactions with PDOUse PDO transactions for related writes, conditional stock updates, rollback cleanup, isolation limits, and safe retry boundaries.
- 74Database Error HandlingHandle PDO and optional MySQLi failures with private logs, useful conflict responses, transaction cleanup, and classified retry policies.
- 75Pagination and Search with SQLBuild PHP search pagination with validated page sizes, prepared values, stable ordering, count queries, and keyset alternatives.
- 76PHP Database Connection Best PracticesStructure PHP database connections with protected configuration, least privilege, utf8mb4, verified transport, and predictable lifecycle rules.
Professional PHP
Configuration, logging, dependencies, standards, testing, performance, deployment and interview practice.
- 77PHP Configuration and php.iniFind PHP's active php.ini, understand CLI versus web settings, configure limits, and apply safe production overrides.
- 78Error Reporting and LoggingConfigure PHP error reporting and private logs, distinguish warnings from exceptions, add request IDs, and avoid sensitive log content.
- 79Composer Dependencies and Version ConstraintsUnderstand Composer require, install, update, caret constraints, lockfiles, platform checks, and controlled dependency upgrades.
- 80PSR Standards and AutoloadingMap PHP namespaces to files with PSR-4 and Composer, understand case-sensitive paths, and distinguish autoloading from other PSR standards.
- 81Environment Variables and .env ConfigurationRead PHP environment variables, validate config types, load .env safely in development, and keep secrets out of public files and logs.
- 82Unit Testing with PHPUnitWrite focused PHP unit tests with PHPUnit, strict assertions, failure cases, and testable boundaries without real mail or production data.
Show all 10 lessonsShow fewer
- 83PHP Performance and OPcache BasicsUnderstand PHP OPcache, measure request bottlenecks, avoid unbounded work, and plan cache invalidation during deployment.
- 84Deployment and Production ConfigurationPlan PHP production releases with locked dependencies, protected secrets, runtime checks, migrations, logs, and a tested rollback path.
- 85PHP Security ChecklistReview PHP input, SQL, output, sessions, uploads, secrets, dependencies, and authorization with practical security checks.
- 86PHP Interview Questions and Coding ExercisesPractice PHP interview questions on types, arrays, OOP, SQL, security, and testable coding tasks with explanations and expected results.
What is PHP?
PHP is a programming language that runs on web servers. When you visit a PHP page, the server runs the PHP code first, and the result, usually HTML, is what gets sent to your browser. That makes PHP ideal for pages that change: a list of products from a database, a "Welcome back, Sam" message or a contact form that sends an email.
PHP powers a huge share of the web, including WordPress, Wikipedia and many online shops, and modern frameworks such as Laravel and Symfony are built with it. It's easy to get started with: a PHP file can be mostly HTML with small pieces of code mixed in where something needs to be dynamic.
How the course is organised
The course has a core path of 25 chapters in three stages, followed by six reference stages:
- Beginner:
echo, variables, strings, decisions, loops, arrays, array functions and your own functions. - Intermediate: includes, forms and validation, sessions and cookies, dates, regular expressions, files, JSON and databases with PDO.
- Advanced: classes, interfaces, traits and enums, exceptions, namespaces and Composer, then a CRUD app, a secure login system, web security and a JSON REST API.
The reference stages go deeper into language fundamentals, arrays and functions, object-oriented PHP, web requests and data formats such as CSV and XML, databases with MySQLi, and professional PHP: configuration, logging, Composer versions, PSR autoloading, PHPUnit, performance, deployment and a security checklist.
How to follow this course
Work through the 25 core chapters in order: they take you from a single page to a complete, secure application. Read a reference lesson when you want more depth on the topic of the core chapter it links to, or when a project needs it. Every lesson has worked examples with their output, common mistakes, exercises, a quiz and frequently asked questions; run the examples with php file.php or the built-in server.
Check your progress with the PHP exercises and the course quiz, and keep the PHP cheat sheet open while you practise. The interview exercises bring the topics together for revision.
It helps to know a little HTML first, because PHP's job is usually to produce it. For storing data, PHP is very often paired with SQL, and JavaScript adds interactivity in the browser.
<!-- php-sql-reference-guide --> Each reference lesson names its prerequisite chapter at the top, so you can always tell what to read first, and every reference adds practice questions to the course quiz.
What you will learn
10 practical skills, built one lesson at a time
- Run PHP with the built-in server and mix PHP into HTML pages
- Work confidently with strings, arrays and PHP's built-in functions
- Handle GET and POST forms and validate input on the server
- Remember visitors with sessions and cookies, and work with dates
- Search and clean text with regular expressions
- Read and write files and JSON, and query MySQL safely with PDO
- Write object-oriented PHP with interfaces, traits, enums and exceptions
- Organise projects with namespaces and install packages with Composer
- Build a complete CRUD app and a secure registration and login system
- Protect sites from XSS, SQL injection and CSRF, and build a REST API
Practise PHP your way
Learning sticks when you use it. Pick a mode.
PHP Exercises
Fill in blanks, predict output and fix broken code with instant feedback.
186 exercisesPHP Quiz
5, 10 or 20 questions with a timer and explanations after every answer.
247 questionsPHP Cheat Sheet
Every important piece of syntax on one printable page.
Open cheat sheetLearning Paths
See where PHP fits in a complete roadmap, and what to learn next.
View learning pathsPHP FAQ
Is PHP still worth learning?
Yes. PHP runs a very large part of the web, WordPress alone powers a big share of all websites, and modern PHP (version 8 and later) is fast, well designed and supported by frameworks like Laravel and Symfony. There are many jobs maintaining and building PHP sites.
What do I need to run PHP?
Install PHP from php.net (on Windows, packages such as XAMPP or Laragon bundle PHP with a database and web server). Then run php -S localhost:8000 in your project folder and open that address in your browser. The first lesson explains the steps.
What's the difference between PHP and JavaScript?
JavaScript usually runs in the browser, on the visitor's device, and changes the page after it loads. PHP runs on the server, before the page is sent, and the visitor never sees the PHP code. Many sites use both.
How long does it take to learn PHP?
With about five hours a week, most learners finish the beginner stage in two to three weeks and the 25 core chapters in two to three months. Building a small project, such as a blog, a guestbook or a to-do list with a database, is the best way to bring the lessons together.
Can PHP work with databases?
Yes, that's one of its main jobs. PHP's PDO extension connects to MySQL, PostgreSQL, SQLite and others, so a PHP page can run SQL queries and turn the results into HTML. The PDO lesson shows how to do it safely.
Is this PHP course free?
Yes. Every lesson, exercise, quiz and the cheat sheet is free to use, with no account or sign-up needed.
Which PHP version does the course use?
The lessons use modern PHP 8, and the examples need PHP 8.1 or newer because they use features such as enums and readonly properties. Where behaviour changed between versions, such as comparisons in PHP 8.0 or new functions in 8.3 and 8.4, the lesson says so.
Should I learn Laravel or plain PHP first?
Learn plain PHP first, at least the core chapters of this course. Laravel and Symfony build on classes, namespaces, Composer, sessions and database access, and understanding them makes framework code far easier to read and debug.
Do I have to read every reference lesson?
No. The 25 core chapters are the main path. Treat the reference stages like a handbook: open the lesson linked to the topic you're working on, or the one a project needs, such as MySQLi, XML or deployment.
More tutorials
Python
A friendly first programming language for scripts, data and automation.
Start PythonJava
A reliable, widely used language for apps, Android and big systems.
Start JavaKotlin
The modern language for Android apps, servers and multiplatform code.
Start KotlinSwift
Apple's fast, safe language for iPhone, iPad, Mac and SwiftUI apps.
Start SwiftC#
Microsoft's versatile language for web APIs, games with Unity and desktop apps.
Start C#C++
A fast, powerful language for games, apps and systems software.
Start C++