Detailed Introduction
PHP is a server-side scripting language built for web development. It exists to help developers generate dynamic web pages, process forms, interact with databases, manage sessions, and build full web applications. Unlike HTML, which structures content, or CSS, which styles it, PHP runs on the server before the page reaches the browser. In real life, PHP powers blogs, e-commerce stores, dashboards, APIs, content management systems like WordPress, and custom business tools. Learning PHP matters because it is practical, widely supported by hosting providers, and beginner-friendly while still being powerful enough for advanced systems.
Core Concepts & Sub-types
What PHP Does
PHP can embed logic into web pages, read user input, perform calculations, send responses, and connect with databases such as MySQL.
Client-Side vs Server-Side
Client-side code runs in the browser. Server-side code runs on the web server. PHP belongs to the server-side category, meaning users do not directly see the PHP source code.
Ways PHP Is Used
PHP is used for dynamic websites, REST APIs, authentication systems, admin panels, file uploads, and automation scripts run from the command line.
Step-by-Step Explanation
PHP code is usually written inside special tags. When a request reaches the server, the PHP engine reads the file, executes the code, and sends the output to the browser. A beginner usually starts by creating a file like index.php, writing PHP inside the tags, and printing output with echo. Statements normally end with a semicolon. Variables start with $, such as $name. Comments can be written with // for a single line. PHP can also be mixed with HTML, which makes it useful for generating dynamic page content.
Comprehensive Code Examples
Basic Example
<?php echo "Hello, PHP!";>Real-world Example
<?php $username = "Aisha";
echo "Welcome back, " . $username . "!";
?>Advanced Usage
<?php $isLoggedIn = true;
$role = "admin";
if ($isLoggedIn && $role === "admin") {
echo "Access granted to admin dashboard.";
} else {
echo "Access denied.";
}
?>These examples show the progression from simple output to dynamic values and then to real application logic using conditions.
Common Mistakes
- Forgetting PHP tags: If code is outside
, it will not execute as PHP. Always check opening tags. - Missing semicolons: Most PHP statements require
;. Add semicolons at the end of statements. - Using wrong file extension: Saving a file as
.htmlinstead of.phpmay prevent server execution. - Opening files directly without a server: PHP must run through a PHP-enabled environment such as XAMPP, Laragon, MAMP, or the built-in PHP server.
Best Practices
- Use meaningful variable names like
$customerNameinstead of vague names like$x. - Keep PHP code readable with consistent spacing and simple structure.
- Test code in a local development environment before deploying.
- Separate logic and presentation as projects grow.
- Read error messages carefully because they often point directly to the issue.
Practice Exercises
- Create a PHP file that prints your name and your learning goal.
- Store your favorite programming language in a variable and display it in a sentence.
- Write a PHP script that checks whether a user is logged in using a boolean variable and prints one of two messages.
Mini Project / Task
Build a small welcome page in PHP that displays a greeting, your name, today's learning topic, and a message that changes based on whether a user is marked as logged in.
Challenge (Optional)
Create a PHP page that stores a user name and role in variables, then shows a different welcome message for an admin, editor, or guest.
Detailed Introduction
PHP stands for Hypertext Preprocessor. It is a server-side scripting language mainly used to build dynamic websites and web applications. Unlike plain HTML, which shows the same content to every visitor unless manually changed, PHP can generate content on the fly based on user input, database data, login status, time, or other conditions. PHP exists to solve a major web problem: making websites interactive and data-driven. In real life, PHP is used in login systems, contact forms, shopping carts, dashboards, content management systems, and APIs. Many popular platforms, including WordPress, are built with PHP. When a user opens a PHP page, the web server processes the PHP code first, then sends the resulting HTML to the browser. This means the browser usually sees the output, not the PHP source code itself.
Core Concepts & Sub-types
Server-side execution
PHP runs on the server, not directly in the browser. The server reads the PHP file, executes the instructions, and returns the final response.
Embedded in HTML
PHP can be written inside HTML files using tags, making it easy to mix logic and page structure.
Procedural and Object-Oriented styles
PHP supports simple procedural coding for beginners and object-oriented programming for larger applications.
Command-line usage
Although PHP is famous for web development, it can also run in the terminal for scripts, automation, and local testing.
Step-by-Step Explanation
A PHP script usually starts with and ends with ?>, though the closing tag is often omitted in pure PHP files. Statements normally end with a semicolon. Variables begin with $, such as $name. To display output, beginners often use echo. A very small script looks like this: open PHP tags, create a variable, and print text. If PHP is inside an HTML page, the server processes the PHP parts and leaves the HTML as normal markup. To run PHP locally, you usually install a stack such as XAMPP, Laragon, MAMP, or use the built-in PHP development server.
Comprehensive Code Examples
Basic example
<?php echo "Hello, PHP!"; ?>Real-world example
<?php $username = "Aisha";
echo "Welcome back, " . $username . "!"; ?>Advanced usage
<?php $hour = date("G");
if ($hour >= 9 && $hour < 18) {
echo "We are currently open.
";
} else {
echo "We are currently closed.
";
}
?>
Common Mistakes
- Opening PHP incorrectly: Writing
instead of . Fix: always use the correct opening tag. - Forgetting semicolons: PHP statements usually require ;. Fix: end each statement properly.
- Trying to open PHP files directly without a server: Double-clicking a PHP file will not execute it. Fix: run it through a local or live web server.
- Mixing PHP and HTML carelessly: Output can break page structure. Fix: keep code organized and test small sections.
Best Practices
- Use clear file names such as index.php or about.php.
- Keep logic simple at first and test each script in small steps.
- Write readable variable names like $userName instead of vague names.
- Use PHP for dynamic tasks and let HTML handle page structure.
- Set up a proper local environment so you can run and debug PHP correctly.
Practice Exercises
- Create a PHP script that prints Hello from PHP.
- Create a variable for your name and display a welcome message using that variable.
- Build a PHP page that shows Good Morning or Good Evening based on a manually set hour variable.
Mini Project / Task
Build a simple dynamic profile welcome page that stores a user's name in a variable and displays a personalized greeting inside an HTML page.
Challenge (Optional)
Create a PHP page that displays a different message depending on the current day of the week, such as a weekday work message or a weekend relaxation message.
Detailed Introduction
PHP stands for PHP: Hypertext Preprocessor. It is a server-side scripting language designed mainly for web development. PHP exists because early web pages were static, meaning they displayed the same content to every visitor. Developers needed a way to generate pages dynamically, process forms, connect to databases, manage sessions, and build interactive websites. PHP solved this problem by allowing code to run on the server before the page was sent to the browser.
PHP was created in 1994 by Rasmus Lerdorf. It started as a small set of Common Gateway Interface tools written in C to track visits to his online resume. Over time, those tools grew into a scripting language used for web applications. PHP became popular because it was simple to start with, easy to embed inside HTML, supported many databases, and worked well on common web servers like Apache. In real life, PHP has powered blogs, e-commerce stores, dashboards, learning platforms, forums, and custom business systems. Famous platforms such as WordPress, Drupal, and Laravel-based applications rely on PHP.
Core Concepts & Sub-types
PHP/FI Era
The earliest version was called Personal Home Page tools, later PHP/FI. It focused on simple web tasks like form handling and visitor tracking.
PHP 3
PHP 3 transformed PHP into a real programming language with improved extensibility and broader adoption. This version helped PHP become widely used in web hosting environments.
PHP 4
PHP 4 introduced the Zend Engine, improving speed and stability. It made PHP suitable for larger websites and more serious production use.
PHP 5
PHP 5 was important because it brought stronger object-oriented programming features, better XML support, and improved database access. This made professional application architecture much easier.
PHP 7 and 8
PHP 7 delivered major performance improvements and lower memory usage. PHP 8 added modern features such as attributes, union types, match expressions, and JIT-related improvements. These versions show PHP evolving into a modern language, not just a beginner tool.
Step-by-Step Explanation
To understand PHP history, think of its growth in stages.
1. It began as a simple utility for personal web pages.
2. Developers started using it for form processing and dynamic content.
3. New engines improved performance and scalability.
4. Object-oriented features made large applications easier to maintain.
5. Modern PHP now supports frameworks, APIs, testing tools, and enterprise patterns.
A beginner should remember one core idea: PHP code runs on the server, generates output such as HTML or JSON, and then sends that result to the browser or client.
Comprehensive Code Examples
Basic example of embedded PHP:
<!DOCTYPE html>
<html>
<body>
<h1><?php echo "Hello from PHP"; ?></h1>
</body>
</html>Real-world example of form processing, one reason PHP became popular:
<?php
$name = $_POST['name'] ?? 'Guest';
echo "Welcome, " . htmlspecialchars($name);
?>Advanced example showing modern PHP style:
<?php
declare(strict_types=1);
function getVersionMessage(int $major): string {
return match ($major) {
5 => 'PHP 5 improved OOP support',
7 => 'PHP 7 greatly improved performance',
8 => 'PHP 8 introduced modern language features',
default => 'Unknown major version'
};
}
echo getVersionMessage(8);
?>Common Mistakes
- Thinking PHP runs in the browser: It runs on the server, and only the output reaches the browser.
- Assuming old PHP reflects modern PHP: Many tutorials show outdated practices. Always check the version and current standards.
- Ignoring security history: Early simple PHP code often lacked validation and escaping. Use modern secure coding habits like
htmlspecialchars()and prepared statements.
Best Practices
- Learn PHP history to understand why many legacy codebases exist.
- Prefer modern PHP 8+ syntax and current frameworks or coding standards.
- Use official documentation to compare features across versions.
- Recognize the difference between legacy embedded PHP and structured modern applications.
Practice Exercises
- Write a short timeline listing at least five important PHP milestones from creation to PHP 8.
- Create a simple PHP file that prints one sentence explaining what server-side scripting means.
- Research and list three real-world platforms or tools built with PHP.
Mini Project / Task
Build a small HTML page with embedded PHP that displays a timeline message such as: Created in 1994, improved in PHP 5, optimized in PHP 7, modernized in PHP 8.
Challenge (Optional)
Create a PHP script that stores major PHP versions in an array and prints a short description for each version in chronological order.
Detailed Introduction
PHP is a server-side scripting language mainly used to build dynamic websites and web applications. Unlike plain HTML, which the browser displays exactly as written, PHP runs on the web server first. The server reads the PHP code, executes it, and sends only the generated outputāusually HTML, JSON, or plain textāto the browser. This matters because sensitive logic such as database queries, authentication, payment processing, and session handling should stay hidden from users. In real life, PHP powers content management systems, e-commerce sites, dashboards, APIs, login systems, and custom business tools. Understanding how PHP works helps beginners see the full request-response cycle: a user requests a page, the server processes PHP, optional database work happens, and the final response is returned to the client.
Core Concepts & Sub-types
Client Side vs Server Side
HTML, CSS, and much of JavaScript run in the browser. PHP runs on the server. The browser never executes raw PHP code directly.
Request and Response Cycle
A browser sends an HTTP request, the web server forwards the PHP file to the PHP engine, the code runs, and the output is returned as an HTTP response.
PHP with Web Servers
PHP commonly works with Apache or Nginx. These servers detect PHP files and pass them to PHP for execution.
PHP Output Types
PHP can generate HTML for web pages, JSON for APIs, redirects for navigation, or files such as CSV downloads.
Step-by-Step Explanation
1. A user enters a URL like /index.php in the browser.
2. The browser sends a request to the web server.
3. The web server sees a PHP file and sends it to the PHP interpreter.
4. PHP executes code between <?php and ?> tags.
5. If needed, PHP reads form data, sessions, files, or databases.
6. PHP builds output, often mixed into HTML.
7. The server sends the final result to the browser.
8. The browser displays the returned content, but not the original PHP source code.
Comprehensive Code Examples
Basic example:
<?php
echo "Hello from PHP!";
?>Real-world example with HTML output:
<!DOCTYPE html>
<html>
<body>
<h1><?php echo "Welcome, User"; ?></h1>
<p>Today is <?php echo date("l"); ?>.</p>
</body>
</html>Advanced usage showing request processing:
<?php
$name = $_GET['name'] ?? 'Guest';
header('Content-Type: application/json');
echo json_encode([
'message' => "Hello, $name",
'time' => date('H:i:s')
]);
?>Common Mistakes
- Trying to open a PHP file directly without a server: Use XAMPP, Laragon, MAMP, Docker, or a configured web server.
- Expecting PHP code to appear in the browser: Only the output is sent, not the source PHP.
- Forgetting PHP tags: Wrap executable code inside
<?php ... ?>. - Mixing output before headers: Call functions like
header()before sending content.
Best Practices
- Keep business logic separate from presentation when possible.
- Use PHP to process data securely on the server, not in the browser.
- Output escaped user data to reduce security risks.
- Learn the full request-response lifecycle before jumping into frameworks.
Practice Exercises
- Create a PHP file that prints a greeting and the current date.
- Build an HTML page that uses PHP to display a dynamic page title.
- Create a PHP script that reads a
namevalue from the URL and prints a personalized message.
Mini Project / Task
Build a simple āserver infoā page that displays the current server time, the visitor IP address, and a custom welcome message generated by PHP.
Challenge (Optional)
Create one PHP file that returns HTML when opened in a browser normally, but returns JSON when the URL contains ?format=json.
Detailed Introduction
Setting up a PHP development environment means preparing the tools needed to write, run, test, and debug PHP applications on your computer. This usually includes PHP itself, a code editor, a local web server such as Apache or Nginx, and often a database like MySQL. It exists to give developers a safe local workspace before deploying code to production. In real life, developers use local environments to build websites, APIs, admin dashboards, e-commerce platforms, and backend services without affecting live users. A good setup improves speed, reduces errors, and makes learning easier because you can instantly test changes.
Core Concepts & Sub-types
PHP Interpreter
The PHP interpreter reads and executes .php files. It can run from the command line or through a web server.
Local Server Stack
Bundles like XAMPP, Laragon, MAMP, or manual setups provide Apache, PHP, and MySQL together. These are beginner-friendly and fast to install.
Code Editor
Editors like VS Code help you write code with syntax highlighting, extensions, and debugging tools.
Package Manager
Composer is PHP's dependency manager. It installs libraries and supports modern project structure.
Environment Variables
These store configuration such as ports, database credentials, and executable paths.
Step-by-Step Explanation
First, install a local server stack or PHP manually. For beginners, XAMPP or Laragon is easiest. Second, install VS Code. Third, confirm PHP works by opening a terminal and running php -v. If it fails, PHP is not in your system PATH. Fourth, create a project folder such as php-basics. Fifth, add a file named index.php. Sixth, write a simple PHP script and run it either in the browser through your local server or in the terminal with php index.php. Seventh, install Composer and verify with composer --version. Finally, keep your project organized with folders like public, src, and vendor for larger projects.
Comprehensive Code Examples
Basic example:
echo "PHP is installed and working!";Real-world example:
$appName = "Local PHP App";
$environment = "development";
echo "Welcome to {$appName}";
echo "
Running in: {$environment}";Advanced usage:
date_default_timezone_set("UTC");
function checkEnvironment(): void {
echo "PHP Version: " . PHP_VERSION . "
";
echo "OS: " . PHP_OS_FAMILY . "
";
echo extension_loaded("pdo") ? "PDO enabled" : "PDO missing";
}
checkEnvironment();Common Mistakes
- PHP not added to PATH: Terminal says command not found. Fix by adding the PHP executable directory to system PATH.
- Saving files with wrong extension: Using
.htmlinstead of.phpprevents PHP execution. Save scripts correctly. - Editing outside server root: Browser cannot find files. Place projects in the correct web directory or configure virtual hosts properly.
- Forgetting to start Apache/MySQL: Local URLs fail. Start required services before testing.
Best Practices
- Use VS Code with PHP extensions for linting and syntax support.
- Learn both browser-based execution and command-line execution.
- Install Composer early because most modern PHP projects depend on it.
- Keep separate folders for experiments and real projects.
- Use a consistent local environment to reduce machine-specific bugs.
Practice Exercises
- Create a folder named
php-env-test, addindex.php, and print a welcome message. - Run
php -vandcomposer --version, then confirm both tools are installed correctly. - Write a PHP file that displays your PHP version and current operating system.
Mini Project / Task
Build a small local project called system-check that shows a page with your app name, PHP version, whether PDO is enabled, and the current date.
Challenge (Optional)
Set up two ways to run the same PHP script: once through the browser using a local server and once through the terminal using the PHP CLI, then compare the outputs.
Detailed Introduction
XAMPP is a local server package that helps you run PHP projects on your own computer without needing a live web hosting account. The name commonly refers to a bundle that includes Apache, MariaDB, PHP, and Perl. For PHP beginners, XAMPP is one of the easiest ways to create a complete development environment because it combines the web server and PHP interpreter into one installable package. In real life, developers use tools like XAMPP to build websites, test forms, connect to databases, and debug applications safely before deployment. Instead of uploading every small change to a remote server, you can work locally, refresh your browser, and see results instantly. This speeds up learning and reduces risk. XAMPP is widely used in classrooms, tutorials, freelance projects, and small development teams because it is simple, free, and cross-platform.
Core Concepts & Sub-types
Apache
Apache is the web server. It listens for requests from your browser and serves PHP files through your local machine.
PHP
PHP is the scripting language that powers dynamic pages. XAMPP installs PHP so your computer can interpret and run .php files.
MariaDB
MariaDB is the database server used to store application data such as users, products, and posts. It is often managed through phpMyAdmin.
phpMyAdmin
phpMyAdmin is a browser-based database management tool included with XAMPP. It helps beginners create databases and tables visually.
Control Panel
The XAMPP Control Panel lets you start and stop services like Apache and MySQL, making environment management easier.
Step-by-Step Explanation
First, visit the official XAMPP website and download the version that matches your operating system. Choose a PHP-compatible build suitable for your course goals. Run the installer and allow permissions if your system asks. During setup, keep the default components unless you have a specific reason to remove one. Install XAMPP in a simple path such as C:\xampp on Windows. After installation, open the XAMPP Control Panel and start Apache and MySQL. If both services turn green, they are running properly. Next, open your browser and go to http://localhost/. If the XAMPP dashboard appears, your local server works. Then place your PHP project inside the htdocs folder, for example C:\xampp\htdocs\myapp. Create a file named index.php and open it through http://localhost/myapp/.
Comprehensive Code Examples
Basic example:
<?php
echo "XAMPP is working!";
?>Real-world example:
<?php
$appName = "Local PHP Store";
echo "<h1>Welcome to {$appName}</h1>";
echo "<p>Your XAMPP environment is ready for development.</p>";
?>Advanced usage:
<?php
phpinfo();
?>This advanced example displays your full PHP configuration, including loaded modules, version details, and server settings. It is useful for checking whether required extensions are enabled.
Common Mistakes
- Mistake: Opening the PHP file directly from the file system. Fix: Always open it through
http://localhost/...so Apache and PHP process it. - Mistake: Saving files outside
htdocs. Fix: Put project files inside the XAMPP web root unless you reconfigure Apache. - Mistake: Apache will not start because port 80 is busy. Fix: Close conflicting apps like Skype, IIS, or other web servers, or change Apache ports.
- Mistake: Forgetting to start MySQL before database work. Fix: Start MySQL from the Control Panel before using phpMyAdmin or database scripts.
Best Practices
- Install XAMPP from the official site only.
- Keep project folders organized inside
htdocswith clear names. - Use
phpinfo()only for testing, then remove it for security. - Stop unused services to reduce conflicts and resource usage.
- Create one folder per practice project for easier learning and debugging.
Practice Exercises
- Install XAMPP and verify the dashboard loads at
http://localhost/. - Create a folder named
php-basicsinsidehtdocsand display a message fromindex.php. - Create a file that runs
phpinfo()and identify your installed PHP version.
Mini Project / Task
Build a small local homepage called my-first-local-site inside htdocs that prints a heading, a short description, and today's date using PHP.
Challenge (Optional)
Change Apache to a different port if port 80 is blocked, then successfully open your project using the new localhost URL.
Detailed Introduction
Running your first PHP script means writing a small PHP program and executing it so the computer interprets the code and produces output. PHP was created to make web pages dynamic, allowing developers to generate HTML, process form data, connect to databases, and automate server-side tasks. In real life, PHP powers blogs, e-commerce stores, dashboards, APIs, content management systems, and internal business tools. Before learning variables, loops, or forms, you must understand how a PHP script starts, where it runs, and what output it produces. A PHP script can run in a browser through a local server such as XAMPP, MAMP, WAMP, or Laravel Valet, and it can also run in the command line using the PHP CLI. This first step is important because it teaches the complete cycle: create a file, write PHP tags, add instructions, save the file, execute it, and verify the result.
Core Concepts & Sub-types
PHP Tags
PHP code usually starts with <?php. This tells the interpreter where PHP begins. Everything inside the tag is processed as PHP code.
Output
The most common first command is echo, which sends text to the browser or terminal. It is often used to confirm that PHP is working correctly.
Execution Environments
PHP scripts can run in two common ways: through a web server for browser-based output, or through the command line for scripts, utilities, and quick testing.
File Extension
PHP files should be saved with the .php extension so the server knows they must be interpreted rather than shown as plain text.
Step-by-Step Explanation
Step 1: Install PHP or a local development stack such as XAMPP. Step 2: Create a new file named index.php. Step 3: Open the file in a code editor like VS Code. Step 4: Add the opening PHP tag <?php. Step 5: Write an output statement such as echo "Hello, PHP!";. Step 6: Save the file. Step 7: If using a server, place the file in the web root folder and open it in the browser. If using the CLI, run php index.php in the terminal. Step 8: Confirm the output appears exactly as expected. Notice the semicolon at the end of the statement. In PHP, most statements end with a semicolon, and forgetting it causes syntax errors.
Comprehensive Code Examples
Basic example:
<?php
echo "Hello, PHP!";Real-world example:
<?php
echo "Welcome to my local PHP app.";
echo "<br>Server is running successfully.";Advanced usage:
<?php
date_default_timezone_set("UTC");
echo "PHP is working.";
echo "<br>Current UTC time: " . date("Y-m-d H:i:s");Common Mistakes
Saving the file as
.htmlinstead of.php. Fix: make sure the file extension is.php.Opening the file directly without a PHP-enabled server when expecting server processing. Fix: use localhost with a local server or run the script with the PHP CLI.
Forgetting the semicolon after
echo. Fix: end statements with;.Using incorrect PHP tags. Fix: always start with
<?php.
Best Practices
Use a proper editor with PHP syntax highlighting and linting.
Name starter files clearly, such as
index.phporhello.php.Test scripts in both browser and terminal when possible to understand execution differences.
Keep first scripts simple so you can isolate setup problems quickly.
Practice Exercises
Create a file named
hello.phpthat prints your name usingecho.Create a script that displays two separate lines of text in the browser.
Run the same PHP file in the browser and in the terminal, then compare the output formatting.
Mini Project / Task
Build a simple startup page called index.php that prints a welcome message, your learning goal, and the current date/time to confirm your PHP environment is working correctly.
Challenge (Optional)
Create one PHP script that detects whether it is being run from the browser or the command line and prints a different welcome message for each environment.
Detailed Introduction
PHP syntax is the set of writing rules that tells the PHP engine how to read and execute your code. It defines how to open PHP tags, create statements, declare variables, write comments, output text, and combine logic into working programs. PHP exists to let developers build dynamic websites and server-side applications, such as login systems, dashboards, APIs, e-commerce stores, and content management systems. In real life, PHP syntax is used whenever a server processes form data, connects to a database, renders HTML dynamically, or handles business logic before sending a page to the browser. Learning syntax first is essential because every advanced PHP topic depends on your ability to read and write correct statements clearly and consistently.
Core Concepts & Sub-types
PHP Tags
PHP code usually starts with <?php and ends with ?>. Inside these tags, the server knows it should execute PHP instead of treating the content as plain HTML.
Statements and Semicolons
Most PHP statements end with a semicolon. It marks the end of an instruction, such as assigning a value or printing output.
Variables
Variables begin with $, like $name. PHP variables are case-sensitive, so $name and $Name are different.
Comments
Use // for single-line comments and /* */ for multi-line comments. Comments help explain code without affecting execution.
Output
PHP commonly uses echo to display text, HTML, or variable values in the browser.
Step-by-Step Explanation
Start by opening a PHP block with <?php. Then write a statement such as assigning data to a variable: $message = "Hello";. End the statement with a semicolon. To display it, write echo $message;. If needed, add comments above important lines to explain purpose. You can also mix PHP with HTML, which is common in server-rendered pages. Keep syntax clean, use meaningful variable names, and be careful with capitalization, quotes, and missing semicolons because small syntax errors can stop execution.
Comprehensive Code Examples
Basic Example
<?php
$name = "Alice";
echo "Hello, " . $name . "!";
?>Real-world Example
<?php
// Simulate user data from a form
$firstName = "Sam";
$city = "Lagos";
echo "<h1>Welcome, $firstName!</h1>";
echo "<p>Your selected city is $city.</p>";
?>Advanced Usage
<?php
declare(strict_types=1);
/* Clean syntax with constants and expressions */
define("SITE_NAME", "PHP Mastery");
$user = "Nina";
$isMember = true;
echo "Welcome to " . SITE_NAME . "<br>";
echo $isMember ? "Access granted for $user" : "Access denied";
?>Common Mistakes
- Forgetting semicolons at the end of statements. Fix: end each instruction with
;unless syntax rules say otherwise. - Using a variable without the
$symbol. Fix: always write variables like$email. - Mixing variable case accidentally. Fix: stay consistent with names like
$userNameand do not switch to$usernameunless intentional. - Breaking quotes in strings. Fix: match opening and closing quotes carefully.
Best Practices
- Always use full PHP opening tags:
<?php. - Choose clear variable names such as
$productNameinstead of$x. - Add comments only where they improve understanding, not for obvious code.
- Keep formatting readable and consistent for easier debugging.
- Test small syntax changes often to catch errors early.
Practice Exercises
- Create a PHP script that stores your name in a variable and prints a greeting message.
- Write a script with two variables, one for a city and one for a country, then display them in one sentence.
- Add both single-line and multi-line comments to a simple PHP file without changing its output.
Mini Project / Task
Build a simple PHP welcome page that defines a user name, membership status, and site title, then prints a personalized message using correct PHP tags, variables, comments, and output syntax.
Challenge (Optional)
Create a mixed PHP and HTML page that displays a different message depending on whether a variable like $isLoggedIn is true or false, while keeping the syntax clean and readable.
Detailed Introduction
PHP comments are notes written inside code that the PHP engine ignores during execution. They exist to help humans understand what the code is doing without affecting program behavior. In real-life projects, comments are used to explain tricky logic, document assumptions, mark temporary work, and make team collaboration easier. For beginners, comments are especially useful for learning because they let you describe each step of your program in plain language. In professional environments, comments appear in application files, configuration scripts, utility functions, and large business systems where developers need to revisit code months later. Good comments improve readability, but unnecessary comments can clutter a file. The goal is not to repeat obvious code, but to clarify intent, rules, and decisions that may not be immediately visible from syntax alone.
Core Concepts & Sub-types
Single-line Comments with //
Use // for short explanations on one line. This is the most common style for quick notes.
Single-line Comments with #
PHP also supports # for one-line comments. It works, but many teams prefer // for consistency.
Multi-line Comments with /* */
Use /* and */ to write comments across multiple lines. This is helpful for longer explanations or temporarily disabling a block of code.
Step-by-Step Explanation
To write a single-line comment, start the line or part of the line with // or #. Everything after that symbol on the same line is ignored by PHP.
For multi-line comments, begin with /*, write your explanation, and close it with */. Anything between these markers is ignored.
Comments can be placed above a variable, beside a statement, or before a block of logic. Use them to explain why code exists, what a value represents, or what a section is expected to do. Avoid using comments as a replacement for clear variable names and clean structure.
Comprehensive Code Examples
<?php
// Basic single-line comment
$name = "Aisha";
echo $name;<?php
# Another single-line comment style
$price = 99.99; // Product price in USD
echo $price;<?php
/*
Real-world example:
Calculate discounted total for a customer order
This discount applies only to premium members
*/
$total = 200;
$isPremiumMember = true;
if ($isPremiumMember) {
$total = $total - 20;
}
echo $total;<?php
/* Advanced usage:
Temporarily disable debug output before deployment
*/
$username = "dev_user";
/*
echo "Debug: " . $username;
print_r($_SERVER);
*/
echo "Application started";Common Mistakes
- Forgetting to close a multi-line comment: Always end
/*comments with*/. - Commenting obvious code: Instead of writing comments like "set x to 5," use meaningful variable names and reserve comments for important explanations.
- Leaving outdated comments: When code changes, update or remove related comments so they do not mislead future developers.
- Using comments to hide broken code permanently: Fix or delete old code instead of leaving large commented blocks in production files.
Best Practices
- Write comments that explain why, not just what.
- Prefer
//for single-line comments to keep style consistent. - Keep comments short, accurate, and easy to scan.
- Use multi-line comments only when the explanation truly needs more detail.
- Remove temporary debug comments before final deployment.
Practice Exercises
- Write a PHP script with two variables and add single-line comments explaining each variable.
- Create a script that uses a multi-line comment to describe what the program does before any code runs.
- Take a small PHP script and add inline comments beside important statements to explain their purpose.
Mini Project / Task
Create a small PHP file for a mock shopping cart total. Add comments to describe the cart value, discount rule, and final output so another beginner can understand the script immediately.
Challenge (Optional)
Write a PHP script with at least five lines of logic and use a combination of single-line, inline, and multi-line comments appropriately without over-commenting obvious code.
Detailed Introduction
PHP variables are named containers used to store data such as text, numbers, true/false values, and more complex values like arrays. They exist so your program can remember information and reuse it later while the script runs. In real life, variables are used everywhere in PHP applications: storing a user name after login, saving product prices in an e-commerce site, tracking form input, calculating totals, and preparing data before sending it to a database or displaying it in HTML. In PHP, every variable starts with a dollar sign, which makes it easy to recognize inside code. Variables are especially important because web applications are dynamic. Instead of hardcoding the same content every time, PHP can place changing values into variables and generate personalized output for each user.
Core Concepts & Sub-types
Naming and Declaration
A variable is created the first time you assign a value to it. Example: $name = "Alice";. Variable names should begin with a letter or underscore and may contain letters, numbers, and underscores.
Data Stored in Variables
Variables can hold strings, integers, floats, booleans, arrays, and null. PHP automatically determines the type based on the assigned value, which is called dynamic typing.
Variable Interpolation
When using double quotes, PHP can insert variable values directly into a string. Example: "Hello, $name".
Reassignment
A variable can change over time. Example: $count = 1; $count = 2;. This is useful when updating totals or statuses.
Step-by-Step Explanation
To use a variable in PHP, follow a simple pattern. First, type the dollar sign. Second, write a meaningful variable name such as $email or $totalPrice. Third, use the assignment operator = to store a value. Finally, end the statement with a semicolon. Example: $age = 25;. You can then output the variable with echo like this: echo $age;. If you want to combine text with variables, use concatenation with a dot, or interpolation inside double quotes. For example: echo "Age: $age"; or echo "Age: " . $age;.
Comprehensive Code Examples
<?php
$name = "Sarah";
$age = 22;
echo "Name: $name";
echo "<br>";
echo "Age: $age";
?><?php
$product = "Laptop";
$price = 899.99;
$inStock = true;
echo "Product: $product";
echo "<br>";
echo "Price: $$price";
echo "<br>";
echo "Available: " . ($inStock ? "Yes" : "No");
?><?php
$firstName = "John";
$lastName = "Doe";
$hourlyRate = 20;
$hoursWorked = 35;
$totalPay = $hourlyRate * $hoursWorked;
$fullName = $firstName . " " . $lastName;
echo "Employee: $fullName";
echo "<br>";
echo "Weekly Pay: $$totalPay";
?>Common Mistakes
- Forgetting the dollar sign: Writing
name = "Sam";is invalid. Use$name = "Sam";. - Using invalid names:
$2nameis not allowed. Start with a letter or underscore. - Mixing quotes incorrectly: Variables do not expand inside single quotes. Use double quotes if you want interpolation.
- Using undefined variables: Outputting a variable before assigning a value may cause warnings. Initialize it first.
Best Practices
- Use clear, descriptive names like
$userEmailinstead of vague names like$x. - Keep naming style consistent, such as camelCase.
- Initialize variables before use to avoid warnings and confusion.
- Store one purpose per variable to keep code readable and easy to debug.
Practice Exercises
- Create variables for your name, age, and favorite color, then print them on separate lines.
- Create variables for a product name and price, then display a simple product summary sentence.
- Create two number variables and a third variable that stores their sum, then print the result.
Mini Project / Task
Build a small PHP profile card using variables for a person's name, job title, city, and years of experience, then display the information in a readable format.
Challenge (Optional)
Create variables for item price, quantity, and tax rate, then calculate and display the final total with a formatted output message.
Detailed Introduction
PHP data types define the kind of value a variable can store, such as text, numbers, true/false values, lists, or more complex structures. They exist so PHP can correctly process, compare, display, and manipulate data in web applications. In real life, data types appear everywhere: a username is a string, a product price is an integer or float, a login status is a boolean, a shopping cart may be an array, and a database record can be represented as an object. Understanding data types is one of the most important beginner skills because every PHP program depends on storing and working with values correctly. PHP is dynamically typed, which means you do not usually declare a variable type manually before assigning a value. Even so, you must still understand what type a value is, because operations behave differently depending on the data. For example, adding numbers is different from joining strings, and checking whether something is true or false affects conditions and loops. A strong grasp of PHP data types helps prevent bugs, improves readability, and prepares you for later topics like functions, forms, arrays, objects, and database work.
Core Concepts & Sub-types
String
A string stores text such as names, emails, and messages. Example: "Hello".
Integer
An integer stores whole numbers like 25 or 1000.
Float
A float stores decimal numbers like 19.99 or 3.14.
Boolean
A boolean stores only true or false, often used in conditions.
Array
An array stores multiple values in one variable, such as a list of products or scores.
Object
An object stores data and behavior together using classes. It is common in larger applications.
NULL
NULL means a variable has no value assigned.
Step-by-Step Explanation
In PHP, variables begin with a dollar sign, such as $name or $age. You assign a value using the equals sign. PHP automatically detects the type based on the assigned value. Text should be wrapped in quotes. Whole numbers do not need quotes. Decimal numbers use a dot. Booleans use the keywords true and false without quotes. Arrays use square brackets. You can inspect a variable type using var_dump(), which is very useful when learning and debugging.
Comprehensive Code Examples
Basic example
<?php
$name = "Alice";
$age = 28;
$price = 49.99;
$isLoggedIn = true;
var_dump($name);
var_dump($age);
var_dump($price);
var_dump($isLoggedIn);Real-world example
<?php
$productName = "Laptop";
$stock = 12;
$discount = 15.5;
$isAvailable = true;
$tags = ["electronics", "work", "portable"];
echo $productName;
echo $stock;
echo $discount;
echo $isAvailable;
print_r($tags);Advanced usage
<?php
class User {
public $name;
public $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
}
$user = new User("Sara", "[email protected]");
$middleName = null;
var_dump($user);
var_dump($middleName);Common Mistakes
Putting numbers in quotes when numeric behavior is expected. Fix: use
25instead of"25"when you need real numeric operations.Using
"true"or"false"as strings instead of booleans. Fix: usetrueandfalsewithout quotes.Forgetting that
NULLis different from an empty string. Fix: check carefully whether a variable should be empty text or truly have no value.
Best Practices
Use meaningful variable names like
$userEmailinstead of vague names like$x.Use
var_dump()while learning to inspect values and types clearly.Keep data types consistent so your code is easier to debug and understand.
Use arrays for grouped data and objects for structured entities with related behavior.
Practice Exercises
Create variables for your name, age, height, and whether you are a student. Display each using
var_dump().Create an array containing five favorite foods and print the full array.
Create a variable with
NULL, then change it to a string and inspect both states.
Mini Project / Task
Build a simple PHP profile card using variables for a person's name, age, salary, employment status, skills array, and an optional nickname set to NULL.
Challenge (Optional)
Create a small script that stores one value of each major PHP data type and outputs a labeled summary showing both the value and its detected type.
Detailed Introduction
PHP constants are fixed values that do not change during script execution. They exist to store important values such as configuration settings, application names, version numbers, tax rates, status labels, and environment-specific values that should remain stable. In real projects, constants are used for things like database modes, file paths, API base URLs, error codes, and feature flags. Unlike variables, constants are not prefixed with $, and once defined, they cannot be redefined or unset in normal use. This makes them useful when you want safety and clarity in your code. For example, if your application uses a company name in many files, defining it once as a constant prevents accidental changes and makes your code easier to maintain.
Core Concepts & Sub-types
Global Constants
These are created with define() and are available globally after definition. They are commonly used in beginner and procedural PHP code.
Constant Expressions with const
The const keyword defines constants in a cleaner way and is often used in modern PHP. It is also used inside classes.
Class Constants
Class constants belong to a class and are accessed with the scope resolution operator ::. They are useful for values related to that class, such as roles, statuses, or fixed configuration.
Magic Constants
PHP also provides built-in special constants like __FILE__, __LINE__, and __DIR__. These are automatically resolved by PHP and are commonly used for debugging and file handling.
Step-by-Step Explanation
To define a constant with define(), write the name first and the value second: define('SITE_NAME', 'PHP Mastery');. The constant name is usually uppercase by convention. To use it, simply write SITE_NAME. With const, write const APP_VERSION = '1.0.0';. For class constants, place const inside a class, then access it like App::STATUS_ACTIVE. Beginners should remember that constants do not use the dollar sign, cannot be changed later, and should be named clearly.
Comprehensive Code Examples
Basic example
define('SITE_NAME', 'Complete PHP Mastery');
const COURSE_LEVEL = 'Beginner to Advanced';
echo SITE_NAME;
echo '
';
echo COURSE_LEVEL;Real-world example
define('TAX_RATE', 0.18);
define('CURRENCY', 'USD');
$price = 200;
$finalPrice = $price + ($price * TAX_RATE);
echo 'Base price: ' . $price . ' ' . CURRENCY;
echo '
';
echo 'Final price: ' . $finalPrice . ' ' . CURRENCY;Advanced usage
class User
{
const ROLE_ADMIN = 'admin';
const ROLE_EDITOR = 'editor';
}
echo User::ROLE_ADMIN;
echo '
';
echo __FILE__;
echo '
';
echo __DIR__;Common Mistakes
- Using a dollar sign: Writing
$SITE_NAMEinstead ofSITE_NAME. Fix: constants are used without$. - Trying to change a constant: Redefining a constant later in code. Fix: choose the correct value before defining it.
- Poor naming: Using unclear names like
dataorx. Fix: use descriptive uppercase names such asMAX_UPLOAD_SIZE. - Confusing constants with variables: Storing changing data in constants. Fix: use variables for values that may change.
Best Practices
- Use constants for values that should never change during execution.
- Prefer uppercase names with underscores for readability.
- Group related constants inside classes when they belong to a specific concept.
- Use magic constants for debugging, paths, and script context.
- Avoid overusing constants for temporary or user-generated values.
Practice Exercises
- Create a constant for your website name and display it.
- Define a constant called
PIand use it to calculate the circumference of a circle. - Create a class named
OrderStatuswith two class constants:PENDINGandCOMPLETED, then print both.
Mini Project / Task
Build a small PHP pricing page that uses constants for company name, tax rate, and currency, then calculates and displays final prices for two products.
Challenge (Optional)
Create a script that uses both user-defined constants and magic constants to display application information such as app name, version, current file, and current directory in a formatted output.
Detailed Introduction
PHP operators are symbols and keywords that let you perform actions on values and variables. They exist so developers can calculate totals, compare values, combine conditions, assign results, and manipulate data efficiently. In real applications, operators are everywhere: adding product prices in a shopping cart, checking whether a user is logged in, comparing form input, assigning defaults, and validating business rules. Without operators, PHP code would be unable to make decisions or transform data. Learning operators well is essential because they appear in almost every script, from simple examples to large production systems.
Core Concepts & Sub-types
Arithmetic Operators
Used for math: +, -, *, /, %, and **.
Assignment Operators
Used to store values in variables, such as =, +=, -=, and .=.
Comparison Operators
Used to compare values: ==, ===, !=, <>, !==, >, <, >=, <=.
Logical Operators
Used to combine conditions: &&, ||, and !.
String Operators
PHP uses . for concatenation and .= to append text.
Increment and Decrement
++ and -- increase or decrease a value by one.
Step-by-Step Explanation
An operator works on one or more operands. In $total = $price + $tax;, the operands are $price and $tax, and the operator is +. Assignment usually happens first when storing results in a variable. Comparison operators return true or false, which are commonly used inside if statements. Logical operators combine multiple comparisons into one rule. For strings, remember PHP does not use + to join text; it uses a dot. Also pay attention to strict comparison: === checks both value and type, making it safer than == in many cases.
Comprehensive Code Examples
Basic example:
<?php
$a = 10;
$b = 3;
echo $a + $b;
echo $a % $b;
echo $a > $b;
?>Real-world example:
<?php
$price = 120;
$discount = 20;
$isMember = true;
$finalPrice = $price - $discount;
if ($isMember && $finalPrice > 50) {
$finalPrice -= 10;
}
echo "Final price: " . $finalPrice;
?>Advanced usage:
<?php
$role = "admin";
$isActive = true;
$loginCount = 5;
$canAccess = ($role === "admin" || $role === "editor") && $isActive && $loginCount >= 1;
echo "Access status: " . ($canAccess ? "allowed" : "denied");
?>Common Mistakes
Using
=instead of==or===in conditions. Fix: use comparison operators when checking values.Using
+to join strings. Fix: use.for concatenation.Relying on
==when types matter. Fix: prefer===for safer comparisons.
Best Practices
Use parentheses to make complex expressions easier to read.
Prefer strict comparisons in authentication, form validation, and API data checks.
Break large expressions into smaller variables for clarity and debugging.
Practice Exercises
Create two number variables and display their sum, difference, product, and remainder.
Write a script that compares two values using both
==and===and observe the result.Create a message using string concatenation with a username and login status.
Mini Project / Task
Build a simple checkout calculator that stores product price, discount, and membership status, then uses arithmetic, assignment, comparison, and logical operators to display the final payable amount.
Challenge (Optional)
Create an access rule that grants entry only if a user is active, has the role of admin or manager, and has logged in more than three times.
Detailed Introduction
PHP conditional statements let your program make decisions based on different situations. Instead of running every line in the same order, your code can choose one action when a condition is true and another when it is false. This exists because real applications must react to user input, login status, form values, prices, roles, and business rules. In real life, conditionals are used to show error messages, validate forms, control page access, apply discounts, and decide what content should appear on a page. Without conditionals, every user would get the same result regardless of context. In PHP, the most common conditional tools are if, else, elseif, switch, and the ternary operator. They work with comparison operators such as ==, ===, !=, >, and logical operators like &&, ||, and !.
Core Concepts & Sub-types
if
Runs a block only when a condition is true.
if...else
Chooses between two paths: one for true and one for false.
if...elseif...else
Checks multiple conditions in sequence until one matches.
switch
Useful when comparing one value against many possible cases.
Ternary Operator
A short form of if...else for simple decisions.
Step-by-Step Explanation
A basic conditional starts with if (condition). The condition must evaluate to true or false. If true, the code inside curly braces runs. You can add else for a fallback block. Use elseif when checking more than two possibilities. For grouped logic, use logical operators. Example: $age >= 18 && $country === 'USA' means both conditions must be true. In a switch, PHP compares one expression to several case values. Add break to stop execution after a match. Use the ternary operator like this: $message = $isLoggedIn ? 'Welcome' : 'Please log in';.
Comprehensive Code Examples
<?php
$age = 20;
if ($age >= 18) {
echo 'You are an adult.';
}<?php
$score = 72;
if ($score >= 90) {
echo 'Grade: A';
} elseif ($score >= 75) {
echo 'Grade: B';
} elseif ($score >= 60) {
echo 'Grade: C';
} else {
echo 'Grade: F';
}<?php
$role = 'editor';
switch ($role) {
case 'admin':
echo 'Full access';
break;
case 'editor':
echo 'Can edit content';
break;
case 'subscriber':
echo 'Read only access';
break;
default:
echo 'Unknown role';
}<?php
$cartTotal = 120;
$isMember = true;
if ($cartTotal >= 100 && $isMember) {
echo 'Discount applied.';
} else {
echo 'No discount available.';
}
$status = $isMember ? 'Member' : 'Guest';
echo $status;Common Mistakes
- Using
=instead of==or===: assignment changes a value; comparison checks it. - Forgetting
breakinswitch: this can cause multiple cases to run unexpectedly. - Using loose comparison carelessly: prefer
===when type matters to avoid surprising results.
Best Practices
- Keep conditions simple and readable.
- Use meaningful variable names such as
$isLoggedInor$hasPermission. - Prefer
===over==when appropriate. - Use
switchfor many fixed value checks on one variable. - Avoid deeply nested conditionals by returning early or restructuring logic.
Practice Exercises
- Write a program that checks whether a number is positive, negative, or zero.
- Create a grade checker using
if...elseif...elsefor five score ranges. - Use
switchto display the day type for values like Monday, Saturday, and Sunday.
Mini Project / Task
Build a simple login feedback script that checks a username role such as admin, editor, or user and prints the correct dashboard message using conditional statements.
Challenge (Optional)
Create a shipping calculator that decides free shipping, standard shipping, or express shipping based on order total, membership status, and destination type using combined conditions.
Detailed Introduction
The if statement is one of the most important decision-making tools in PHP. It allows your program to check whether a condition is true and then run specific code only when that condition matches. Without conditional logic, applications would behave the same way every time, regardless of user input, data, or system state. In real life, PHP uses if statements everywhere: checking whether a user is logged in, validating form input, deciding whether an order qualifies for free shipping, showing admin-only pages, or preventing access when permissions are missing. Think of it as teaching your program how to make choices. If a student passes an exam, show a success message. If a product is out of stock, disable checkout. If a password is incorrect, deny login. These are all common, practical uses of if statements. For beginners, mastering this topic is essential because almost every PHP application depends on conditions to control flow and produce the right output at the right time.
Core Concepts & Sub-types
Simple if
Runs a block only when a condition evaluates to true.
if...else
Provides an alternative block when the condition is false.
if...elseif...else
Checks multiple conditions in order and executes the first matching block.
Nested if
Places one if statement inside another for more detailed decision logic.
Step-by-Step Explanation
Basic syntax looks like this: if (condition) { code to run; }. First, PHP evaluates the expression inside the parentheses. If the result is true, the block inside curly braces executes. If false, PHP skips it. With else, you add a fallback block. With elseif, you test more conditions in sequence. Conditions usually use comparison operators such as ==, ===, !=, >, <, >=, and <=, often combined with logical operators like && and ||. Always wrap your condition clearly and use braces, even for one line, because it improves readability and reduces mistakes.
Comprehensive Code Examples
Basic example
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
}Real-world example
$isLoggedIn = true;
$isAdmin = false;
if ($isLoggedIn && $isAdmin) {
echo "Welcome, Admin.";
} elseif ($isLoggedIn) {
echo "Welcome, User.";
} else {
echo "Please log in.";
}Advanced usage
$total = 120;
$hasCoupon = true;
if ($total >= 100) {
if ($hasCoupon) {
echo "Apply premium discount.";
} else {
echo "Apply standard discount.";
}
} else {
echo "No discount available.";
}Common Mistakes
- Using
=instead of==or===. Fix: use comparison operators for checking values. - Forgetting braces and causing unclear logic. Fix: always include curly braces, even for single-line blocks.
- Using loose comparisons carelessly. Fix: prefer
===when type matters. - Writing conditions in the wrong order with
elseif. Fix: place more specific conditions before broader ones.
Best Practices
- Keep conditions simple and readable.
- Use meaningful variable names like
$isLoggedInor$hasAccess. - Prefer strict comparison when possible.
- Avoid deeply nested if blocks unless necessary.
- Add comments only when the business rule is not obvious from the code.
Practice Exercises
- Create a variable for age and print whether the person is eligible to vote.
- Create a variable for a number and print whether it is positive, negative, or zero using
if...elseif...else. - Create a variable for a password length and print whether it is valid if it has at least 8 characters.
Mini Project / Task
Build a simple PHP access checker that displays different messages for guests, logged-in users, and admins based on boolean variables.
Challenge (Optional)
Write a grading script that takes a numeric score and prints A, B, C, D, or F using properly ordered if...elseif...else conditions.
Detailed Introduction
The if else statement is one of the most important decision-making tools in PHP. It allows your program to choose between different actions based on whether a condition is true or false. Without conditional logic, every PHP script would run the same way every time, regardless of user input, data values, or application state. In real life, websites and apps constantly make decisions using if else logic: checking whether a user is logged in, verifying if a form field is empty, deciding whether an order qualifies for free shipping, or showing different content to admins and regular users. In PHP, conditions usually compare values using operators such as ==, ===, >, <, >=, and <=. If the condition evaluates to true, one block of code runs; otherwise, another block can run. This makes if else statements essential for building dynamic applications. As a beginner, learning if else statements helps you control program flow and write smarter code that reacts to changing situations.
Core Concepts & Sub-types
if
Runs a block only when a condition is true.
if else
Runs one block if the condition is true and another block if it is false.
if elseif else
Checks multiple conditions in order. The first true condition runs, and the rest are skipped.
Nested if
Places one if statement inside another. This is useful for more detailed decision-making, though it should be kept readable.
Step-by-Step Explanation
The basic syntax starts with the if keyword, followed by a condition inside parentheses, then curly braces containing the code to execute. Example structure: if (condition) { // code }. For an alternative path, add else. For multiple checks, use elseif between them. PHP reads the condition from left to right, evaluates it as true or false, and executes the matching block. Conditions often use comparison operators and logical operators such as && for AND and || for OR. Always use braces, even for a single line, because it improves clarity and reduces mistakes.
Comprehensive Code Examples
Basic example:
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}Real-world example:
$isLoggedIn = true;
$role = "admin";
if ($isLoggedIn && $role === "admin") {
echo "Welcome, Admin!";
} elseif ($isLoggedIn) {
echo "Welcome, User!";
} else {
echo "Please log in first.";
}Advanced usage:
$score = 82;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} elseif ($score >= 60) {
echo "Grade: D";
} else {
echo "Grade: F";
}Common Mistakes
- Using = instead of
==or===in conditions. Fix: use comparison operators, not assignment. - Forgetting braces and creating confusing logic. Fix: always include curly braces.
- Using
==when strict comparison is safer. Fix: prefer===when type matters. - Placing broader conditions before specific ones. Fix: check more specific cases first in an
elseifchain.
Best Practices
- Keep conditions simple and readable.
- Use meaningful variable names like
$isAdminor$hasAccess. - Prefer strict comparisons with
===and!==. - Avoid deeply nested if statements when possible; split logic into smaller checks.
- Order conditions carefully from most specific to most general.
Practice Exercises
- Write a PHP script that checks whether a number is positive or negative using
if else. - Create a script that checks a user age and prints whether they can vote.
- Build an
if elseif elseprogram that prints a grade label based on a numeric score.
Mini Project / Task
Build a simple discount checker that prints one message for premium members, another for regular members, and a third for guests who are not logged in.
Challenge (Optional)
Create a PHP script that accepts a temperature value and prints whether the weather is cold, warm, or hot, then add a second nested condition to suggest clothing advice for each category.
Detailed Introduction
The switch statement in PHP is a control structure used to compare one value against multiple possible cases. It exists to make decision-making code cleaner than writing many if, elseif, and else blocks when all conditions depend on the same variable. In real applications, developers use switch for menu systems, status handling, role-based messages, API response mapping, and routing user choices. For example, if a user selects a payment method, account type, or command option, switch can evaluate that single input and run the matching block of code. This makes code easier to read, organize, and maintain, especially when there are several fixed known values.
Core Concepts & Sub-types
Standard switch-case
This is the most common form. PHP checks the switch expression, then compares it with each case. When a match is found, that block runs.
break statement
The break keyword stops execution inside the switch. Without it, PHP continues into the next case. This is called fall-through.
default case
The default block runs when no case matches. It works like the final fallback option.
Fall-through behavior
Sometimes developers intentionally omit break so multiple cases share the same output. This is useful when several values should lead to the same result.
Step-by-Step Explanation
The syntax begins with switch (expression). Inside curly braces, you add case value: labels. Under each case, place the code to execute. Usually, you finish each case with break;. Finally, add an optional default: block. PHP evaluates the expression once, then checks each case until it finds a match. If matched, that case runs. If no case matches, default runs if it exists. This structure is best when comparing one variable to a list of exact known values.
Comprehensive Code Examples
Basic example
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week";
break;
case "Friday":
echo "Weekend is near";
break;
default:
echo "Regular day";
}Real-world example
$role = "editor";
switch ($role) {
case "admin":
echo "Full dashboard access";
break;
case "editor":
echo "Can edit and publish content";
break;
case "subscriber":
echo "Can view member content";
break;
default:
echo "Unknown role";
}Advanced usage
$status = 201;
switch ($status) {
case 200:
case 201:
echo "Request succeeded";
break;
case 400:
echo "Bad request";
break;
case 401:
case 403:
echo "Access denied";
break;
default:
echo "Unhandled status code";
}Common Mistakes
- Forgetting
break: This causes unintended fall-through. Addbreak;unless you intentionally want shared behavior. - Using
switchfor complex conditions:switchis best for fixed values, not range checks like greater than or less than. Useifstatements for those cases. - Skipping
default: Without a fallback, unmatched values produce no result. Adddefaultto handle unexpected input safely.
Best Practices
- Use
switchonly when comparing one expression to multiple exact values. - Always include a
defaultblock for safer code. - Keep each case short and readable.
- Group related cases with intentional fall-through when they share the same output.
- Use meaningful variable names like
$status,$role, or$command.
Practice Exercises
- Create a
switchstatement that prints a message for each day number from 1 to 3, with a default message for other numbers. - Build a
switchthat checks a traffic light color such asred,yellow, orgreenand prints the correct driving instruction. - Write a
switchstatement that takes a letter grade likeA,B, orCand prints a matching performance message.
Mini Project / Task
Build a simple command-based menu for a console-style PHP script. Store a user choice such as view, edit, delete, or exit in a variable, then use a switch statement to display the correct action message.
Challenge (Optional)
Create a PHP script that accepts an HTTP-like status code and uses switch to group related responses, such as success, client errors, and authorization errors, while sharing output for multiple cases where appropriate.
Detailed Introduction
Loops in PHP are control structures that let you repeat a block of code multiple times without writing the same statement again and again.
They exist to automate repetitive tasks such as printing values, processing arrays, reading database results, generating HTML elements, and validating repeated user input.
In real applications, loops are used everywhere: showing product lists in an online store, calculating totals from shopping carts, sending emails to many users, or building reports from records. Instead of manually writing code for each item, a loop handles repetition efficiently and makes programs shorter, cleaner, and easier to maintain.
Core Concepts & Sub-types
for Loop
Best when you know how many times the loop should run. It uses initialization, condition, and increment/decrement in one statement.
while Loop
Runs as long as a condition remains true. It is useful when the number of repetitions is not fixed beforehand.
do-while Loop
Similar to while, but it always executes the code at least once before checking the condition.
foreach Loop
Designed for arrays and iterable data. It is the most readable way to access each item in a collection.
Step-by-Step Explanation
A for loop follows this pattern: start a variable, test a condition, then update the variable after each round.for ($i = 1; $i <= 5; $i++) means: start at 1, continue while 1 through 5 are valid, and increase by 1 each time.
A while loop checks the condition first, so if the condition is false immediately, it never runs.
A do-while loop runs once first, then checks the condition.foreach reads arrays item by item using syntax like foreach ($items as $item) or foreach ($items as $key => $value).
Comprehensive Code Examples
Basic example:
for ($i = 1; $i <= 5; $i++) {
echo "Count: $i
";
}Real-world example:
$products = ["Laptop", "Mouse", "Keyboard"];
foreach ($products as $product) {
echo "$product ";
}Advanced usage:
$orders = [
["id" => 101, "total" => 250],
["id" => 102, "total" => 400],
["id" => 103, "total" => 150]
];
$grandTotal = 0;
foreach ($orders as $order) {
$grandTotal += $order["total"];
echo "Order #" . $order["id"] . " - $" . $order["total"] . "
";
}
echo "Grand Total: $" . $grandTotal;Using while with user-style counting:
$x = 1;
while ($x <= 3) {
echo "Step $x
";
$x++;
}Common Mistakes
- Infinite loops: forgetting to update the counter. Fix by incrementing or changing the condition correctly.
- Wrong condition: using
<instead of<=and missing the final value. Fix by checking boundary logic carefully. - Using foreach on non-arrays: causes warnings. Fix by ensuring the variable is an array or iterable first.
Best Practices
- Use
foreachfor arrays because it is clearer and safer. - Keep loop bodies small and readable; move complex logic into functions when needed.
- Avoid deeply nested loops unless necessary, as they reduce readability and may affect performance.
- Choose meaningful variable names like
$productor$index.
Practice Exercises
- Write a
forloop that prints numbers from 1 to 10. - Create a
whileloop that prints all even numbers from 2 to 20. - Use
foreachto display each color from an array of five colors.
Mini Project / Task
Build a simple PHP script that stores five student names in an array and uses a loop to print them as an HTML unordered list.
Challenge (Optional)
Create a loop-based script that prints numbers from 1 to 30, but for multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.
Detailed Introduction
The
for loop is a fundamental control flow statement in PHP, allowing you to execute a block of code a specific number of times. It's an essential tool for iterating over sequences, processing arrays, or performing repetitive tasks where the number of iterations is known before the loop begins. Imagine you need to print numbers from 1 to 10, calculate the sum of the first 100 integers, or iterate through a list of items a fixed number of times. The for loop provides a concise and structured way to handle such scenarios. It's particularly useful when you have a clear starting point, an ending condition, and a consistent way to progress through each iteration.Core Concepts & Sub-types
There aren't 'sub-types' of the
for loop itself, but rather other loop constructs in PHP that serve different iteration needs. The for loop is distinguished by its explicit initialization, condition, and increment/decrement expressions. Other loops include while (for indefinite loops), do-while (similar to while but executes at least once), and foreach (specifically for iterating over arrays and objects). The for loop's strength lies in its ability to encapsulate all loop control logic in a single line, making it highly readable for fixed-iteration tasks.Step-by-Step Explanation
The
for loop in PHP has a distinct syntax:for (initialization; condition; increment/decrement) {
// Code to be executed repeatedly
}
Let's break down each part:
- Initialization: This expression is executed once at the very beginning of the loop. It's typically used to declare and initialize a loop counter variable (e.g.,
$i = 0). - Condition: This expression is evaluated before each iteration. If it evaluates to
true, the loop continues; iffalse, the loop terminates. - Increment/Decrement: This expression is executed at the end of each iteration, after the loop's code block has run. It's typically used to update the loop counter (e.g.,
$i++or$i--).
The loop continues as long as the condition remains true. Once the condition becomes false, the loop exits, and the program continues with the code following the loop block.
Comprehensive Code Examples
Basic example: Printing numbers from 1 to 5
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "
";
}
?>Real-world example: Calculating the sum of an array's elements
$numbers = [10, 20, 30, 40, 50];
$sum = 0;
for ($i = 0; $i < count($numbers); $i++) {
$sum += $numbers[$i];
}
echo "The sum of the numbers is: " . $sum . "
";
?>Advanced usage: Nested for loops for a multiplication table
echo "";
for ($i = 1; $i <= 10; $i++) {
echo "";
for ($j = 1; $j <= 10; $j++) {
echo "";
}
echo "";
}
echo "" . ($i * $j) . "
";
?>Common Mistakes
- Off-by-one errors: Using
<instead of<=(or vice versa) can cause the loop to run one too many or one too few times. Always double-check your condition. - Infinite loops: If the condition never evaluates to
false, the loop will run indefinitely, potentially crashing your script or server. Ensure the increment/decrement step correctly progresses towards making the condition false. Example:for ($i = 0; $i < 5; $i--). - Incorrect variable scope: Forgetting to declare the loop variable within the initialization or trying to use it outside its intended scope (though in PHP, variables defined in a loop usually persist outside it, it's good practice to be mindful).
Best Practices
- Clear variable names: Use descriptive variable names for your loop counters (e.g.,
$index,$count) rather than just$i, especially in complex loops. - Initialize variables properly: Always ensure your loop counter and any other variables used within the loop are initialized correctly.
- Keep conditions simple: Complex conditions can make loops harder to read and debug. If a condition is very complex, consider breaking it down or moving parts of it into helper functions.
- Avoid modifying the loop counter inside the loop body (unless intentional): Changing
$iwithin the loop's body can lead to unexpected behavior and make the loop flow difficult to follow.
Practice Exercises
- Write a
forloop to print all even numbers from 2 to 20. - Create a
forloop that iterates from 10 down to 1 and prints each number. - Use a
forloop to calculate the factorial of 5 (1 * 2 * 3 * 4 * 5).
Mini Project / Task
Build a PHP script that uses a
for loop to generate a simple HTML ordered list (). Each list item should display "Item #X", where X is the item number from 1 to 10.Challenge (Optional)
Write a PHP script that generates a pyramid pattern of asterisks (*) using nestedforloops. The pyramid should have 5 rows. For example:*
**
***
****
*****
) containing 10 list items (Detailed Introduction
The while loop in PHP is a control structure used to repeat a block of code as long as a condition remains true. It exists so developers do not have to manually write the same statements again and again. Instead of copying code ten times, you can let the loop run automatically until a stopping condition is reached.
In real projects, while loops are useful when the number of repetitions is not fixed in advance. For example, you may keep reading user input until a valid value is entered, process database records one row at a time, or continue retrying an operation until it succeeds or reaches a limit. The while loop is especially helpful when logic depends on changing values during execution.
Core Concepts & Sub-types
while
The while loop checks the condition before running the code block. If the condition is false from the beginning, the loop will not execute at all.
Related loop: do-while
Although this lesson focuses on while, beginners should know that do-while is closely related. A do-while loop runs the code first and checks the condition afterward, meaning it executes at least once.
Step-by-Step Explanation
The syntax is simple: write while (condition) followed by a block of code in braces.
Step 1: Create a variable that will control the loop.
Step 2: Write a condition that returns true or false.
Step 3: Place the repeated code inside the loop block.
Step 4: Update the control variable so the loop eventually stops.
General syntax:
$counter = 1;
while ($counter <= 5) {
echo $counter . "
";
$counter++;
}
?>Here, PHP checks whether $counter <= 5. If true, it prints the value, increases it by one, and checks again. When the condition becomes false, the loop ends.
Comprehensive Code Examples
Basic example
$i = 1;
while ($i <= 3) {
echo "Iteration: " . $i . "
";
$i++;
}
?>Real-world example
$attempts = 1;
$maxAttempts = 3;
while ($attempts <= $maxAttempts) {
echo "Login attempt $attempts
";
$attempts++;
}
echo "Account temporarily locked.";
?>Advanced usage
$number = 20;
while ($number > 0) {
if ($number % 4 === 0) {
echo $number . " is divisible by 4
";
}
$number--;
}
?>This example combines a while loop with a conditional statement, showing how loops often work together with other logic.
Common Mistakes
- Forgetting to update the loop variable: This causes an infinite loop. Always change the variable inside the loop.
- Using the wrong condition: A condition like
$i >= 5instead of$i <= 5may prevent the loop from running. - Starting with the wrong initial value: If the variable begins outside the expected range, the output may be incorrect or skipped entirely.
- Changing the variable incorrectly: Increasing when you should decrease, or decreasing too much, can break the logic.
Best Practices
- Always make sure the loop has a clear ending condition.
- Use meaningful variable names such as
$counter,$attempts, or$index. - Keep loop bodies simple and readable.
- Use comments when the stopping logic is not obvious.
- Test edge cases, such as when the loop should run zero times or only once.
Practice Exercises
- Create a while loop that prints numbers from 1 to 10.
- Write a while loop that prints all even numbers from 2 to 20.
- Make a countdown from 5 to 1 using a while loop.
Mini Project / Task
Build a simple PHP script that simulates 5 retry attempts for connecting to a server. Use a while loop to print each attempt number and stop after the fifth try.
Challenge (Optional)
Write a while loop that starts at 1 and keeps adding numbers until the total becomes greater than 50. Print each number added and the final sum.
Detailed Introduction
The do...while loop in PHP is a control structure that runs a block of code first, then checks a condition afterward. This makes it different from a regular while loop, which checks the condition before running. The main reason the do...while loop exists is to guarantee that the code inside the loop executes at least once. This is useful in real applications when you want to display a menu, process user input, retry an operation, or keep asking for valid data until the requirement is met. For example, a login retry system, a command-line menu, or repeated form validation logic can benefit from this structure. It is especially helpful when the first run must happen before deciding whether to continue.
Core Concepts & Sub-types
Do-While Loop
The do...while loop executes the code block once before evaluating the condition. If the condition is true, it continues repeating. If false, it stops after the first execution.
Compared with While
A while loop may run zero times if the condition is false from the beginning, but a do...while loop always runs at least once. This is the key difference students must remember.
Step-by-Step Explanation
The syntax is:
do {
// code to execute
} while (condition);Here is how it works step by step:
1. PHP enters the do block immediately.
2. The code inside the braces runs.
3. PHP checks the condition in while (condition).
4. If the condition is true, the loop repeats.
5. If the condition is false, the loop ends.
Notice the semicolon after the while(...) statement. It is required in PHP syntax.
Comprehensive Code Examples
Basic Example
$i = 1;
do {
echo $i . "
";
$i++;
} while ($i <= 5);This prints numbers 1 to 5. The variable increases after each loop until the condition becomes false.
Real-World Example
$attempt = 1;
do {
echo "Processing login attempt $attempt
";
$attempt++;
} while ($attempt <= 3);This simulates allowing a user up to three login attempts.
Advanced Usage
$number = 100;
do {
echo "Current value: $number
";
$number -= 15;
if ($number <= 40) {
break;
}
} while ($number > 0);This example shows a loop with a decreasing value and a break statement for early termination.
Common Mistakes
- Forgetting the semicolon after
while(condition);. Fix: always end the statement properly. - Creating an infinite loop by not updating the loop variable. Fix: change the variable inside the loop so the condition can become false.
- Using
do...whilewhen zero executions are acceptable. Fix: usewhileinstead if the condition should be checked first.
Best Practices
- Use
do...whileonly when at least one execution is required. - Keep the loop condition simple and readable.
- Update loop variables clearly to avoid bugs.
- Use
breakcarefully and only when it improves clarity.
Practice Exercises
- Write a
do...whileloop that prints numbers from 1 to 10. - Create a loop that prints even numbers from 2 to 20 using
do...while. - Write a loop that starts at 5 and counts down to 1.
Mini Project / Task
Build a simple retry system that displays a message for each attempt and stops after 3 tries using a do...while loop.
Challenge (Optional)
Create a do...while loop that keeps adding numbers starting from 1 until the total becomes greater than 50, then print the final sum and the last number added.
Detailed Introduction
The foreach loop in PHP is a control structure made specifically for iterating over arrays and iterable data. Instead of manually managing a counter like you would with a for loop, foreach automatically moves through each item one by one. This makes code easier to read, safer for beginners, and ideal for tasks where you need to process lists of values such as product names, user records, form inputs, menu links, or configuration settings. In real applications, developers use foreach to display database results, generate HTML lists, calculate totals, transform data, and inspect associative arrays returned by APIs. It exists because looping through collections is one of the most common programming tasks, and PHP provides a specialized structure to do it clearly and efficiently.
Core Concepts & Sub-types
Value-only foreach
This form loops through each array item and gives you only the value. It is useful when you do not need the index or key.
Key-value foreach
This version gives both the key and the value. It is commonly used with associative arrays, where keys have meaningful names like name or email.
Foreach by reference
Using & lets you modify the original array values directly during iteration. This is powerful, but it must be used carefully to avoid accidental changes.
Step-by-Step Explanation
Basic syntax: foreach ($array as $item). PHP takes the array, reads each element in order, and stores the current value in $item during each loop cycle. For associative arrays, use foreach ($array as $key => $value). Here, $key stores the array key and $value stores the related value. If you need to change original values, use foreach ($array as &$item). After a reference loop, it is good practice to unset the loop variable so it does not keep pointing to the last element.
Comprehensive Code Examples
Basic example
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color . "
";
}Real-world example
$user = [
"name" => "Ava",
"email" => "[email protected]",
"role" => "Editor"
];
foreach ($user as $field => $value) {
echo ucfirst($field) . ": " . $value . "
";
}Advanced usage
$prices = [100, 200, 300];
foreach ($prices as &$price) {
$price = $price * 1.10;
}
unset($price);
foreach ($prices as $finalPrice) {
echo $finalPrice . "
";
}Common Mistakes
- Using
foreachon a non-array value. Fix: make sure the variable contains an array or iterable before looping. - Expecting the original array to change without using references. Fix: use
&$itemwhen direct modification is intended. - Forgetting
unset($item)after a reference loop. Fix: always unset the reference variable after the loop ends.
Best Practices
- Use clear variable names like
$product,$student, or$price. - Choose key-value syntax for associative arrays to make your code self-explanatory.
- Avoid modifying arrays by reference unless truly necessary.
- Keep loop bodies focused; move complex logic into functions if needed.
Practice Exercises
- Create an indexed array of five fruit names and print each one using
foreach. - Create an associative array for a book with keys like
title,author, andyear, then print both keys and values. - Create an array of numbers and use a reference-based
foreachloop to increase each number by 5.
Mini Project / Task
Build a PHP script that stores a shopping cart in an array and uses foreach to display each item with its price, then calculate and print the total cost.
Challenge (Optional)
Create a nested array of students, where each student has a name and marks, then use foreach loops to print each student and their average score.
Detailed Introduction
In PHP, break and continue are loop-control statements used to change the normal flow of repetition. They exist because sometimes a loop should not always run every remaining iteration in the same way. break stops the loop entirely, while continue skips the current iteration and moves to the next one. These statements are common in for, while, do-while, and foreach loops. In real applications, they are useful when searching for a value, ignoring invalid records, stopping once a condition is met, filtering user input, or exiting nested processing early. Learning them helps you write more efficient and readable logic instead of forcing unnecessary iterations.
Core Concepts & Sub-types
break
break immediately ends the current loop. Execution continues with the first statement after the loop. It is helpful when the goal has already been achieved, such as finding a matching product ID.
continue
continue skips the rest of the current iteration and jumps to the next cycle of the loop. It is useful when some items should be ignored, such as empty form values or banned usernames.
Using levels in nested loops
PHP also allows break 2 or continue 2 in nested structures. The number tells PHP how many levels to affect. This is advanced but useful when one condition should exit or skip more than one loop.
Step-by-Step Explanation
Inside a loop, PHP evaluates each iteration from top to bottom. If break; is reached, the loop stops completely. If continue; is reached, PHP skips the remaining code in that iteration and starts the next one. Syntax is simple: place the statement inside a conditional block when a certain rule is met. Example pattern: check a condition, then either stop the loop with break or skip unwanted data with continue. These statements should be used deliberately so the loop behavior remains easy to understand.
Comprehensive Code Examples
Basic example
for ($i = 1; $i <= 10; $i++) {
if ($i == 6) {
break;
}
echo $i . " ";
}
echo "
";
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo $i . " ";
}
?>Real-world example
$users = ["Anna", "", "David", "", "Maria"];
foreach ($users as $user) {
if ($user === "") {
continue;
}
echo "Processing user: " . $user . "
";
}
?>Advanced usage
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
foreach ($matrix as $row) {
foreach ($row as $value) {
if ($value == 5) {
break 2;
}
echo $value . " ";
}
}
?>In the advanced example, break 2 exits both loops as soon as the value 5 is found.
Common Mistakes
Using
breakwhen you only want to skip one item. Fix: usecontinueinstead.Placing code after
continueand expecting it to run in the same iteration. Fix: remember that remaining code in that cycle is skipped.Overusing
breakandcontinuein complex loops, making logic hard to read. Fix: keep conditions clear and consider refactoring into functions.
Best Practices
Use
breakfor early exit only when it improves efficiency or readability.Use
continueto filter invalid or unwanted data quickly.Add meaningful conditions before these statements so future readers understand why flow changes.
Be careful with nested loops and level-based control like
break 2.Test edge cases, especially when stopping loops early affects later logic.
Practice Exercises
Write a
forloop from 1 to 20 and stop it when the number reaches 12.Use a
foreachloop to print names from an array, but skip any empty strings.Create a loop that prints numbers from 1 to 15 but skips all multiples of 4.
Mini Project / Task
Build a PHP script that loops through a list of product prices, skips invalid negative values using continue, and stops completely using break once a price greater than 1000 is found.
Challenge (Optional)
Create a nested loop that searches a two-dimensional array for a target number and exits both loops immediately when the match is found.
Detailed Introduction
Functions in PHP are reusable blocks of code that perform a specific task. Instead of writing the same logic again and again, you define it once and call it whenever needed. This improves readability, reduces duplication, and makes programs easier to test and maintain. In real projects, functions are used for tasks like formatting prices, validating form input, sending emails, generating slugs, or calculating totals in shopping carts. PHP provides many built-in functions such as strlen() and date(), and it also allows you to create custom functions for your own application logic.
Core Concepts & Sub-types
Built-in Functions
These are functions already provided by PHP, such as count(), explode(), and in_array().
User-defined Functions
These are custom functions you create using the function keyword to solve specific problems in your project.
Functions with Parameters
Parameters allow data to be passed into a function, making it dynamic and reusable.
Functions with Return Values
A function can send a result back using return, which is useful for calculations and transformations.
Default and Typed Parameters
PHP supports default values and type declarations to make functions safer and clearer.
Step-by-Step Explanation
To create a function, use the function keyword, followed by a name, parentheses, and a code block. Example structure: function greet($name) { return "Hello " . $name; }. First, choose a meaningful name. Second, add parameters if input is needed. Third, write the function body. Fourth, use return if the function should produce a value. Finally, call the function using its name and required arguments, such as greet("Sara"). Beginners should remember that defining a function does not run it; it only becomes available for later use.
Comprehensive Code Examples
Basic example
function sayHello() {
echo "Hello, World!";
}
sayHello();Real-world example
function formatPrice(float $amount, string $currency = "USD"): string {
return $currency . " " . number_format($amount, 2);
}
echo formatPrice(199.99);
echo formatPrice(49.5, "EUR");Advanced usage
function calculateCartTotal(array $prices, float $taxRate = 0.1): float {
$subtotal = array_sum($prices);
$tax = $subtotal * $taxRate;
return $subtotal + $tax;
}
$items = [29.99, 15.50, 9.99];
echo calculateCartTotal($items);Common Mistakes
- Forgetting to call the function: defining a function alone does nothing. Always call it after definition.
- Missing required arguments: if a function expects parameters, pass them correctly or provide defaults.
- Using
echoinstead ofreturnwhen a value is needed later: usereturnfor reusable results, andechoonly for output.
Best Practices
- Use clear, action-based names like
calculateTotal()orvalidateEmail(). - Keep each function focused on one job only.
- Use type declarations for parameters and return values when possible.
- Avoid very large functions; break them into smaller reusable pieces.
- Document expected inputs and outputs through naming and consistent structure.
Practice Exercises
- Create a function named
squareNumber()that accepts one number and returns its square. - Write a function named
isAdult()that takes an age and returns whether the user is 18 or older. - Build a function named
greetUser()that accepts a name and an optional greeting word.
Mini Project / Task
Create a small invoice helper with functions to calculate subtotal, tax, and final total from an array of item prices.
Challenge (Optional)
Write a function that accepts a string and returns a word count array showing how many times each word appears.
Detailed Introduction
Function parameters are placeholders defined in a function so it can receive input values when called. They exist to make functions reusable, flexible, and easier to maintain. Instead of writing separate functions for every small variation, you write one function and pass different values into it. In real projects, parameters are used everywhere: calculating totals in shopping carts, formatting usernames, validating form input, filtering records, and sending configuration values into reusable utilities. In PHP, parameters let you control how a function behaves without changing the function body each time. This is a core part of writing clean, modular code.
Core Concepts & Sub-types
Required Parameters
These must be provided when calling the function. If they are missing, PHP throws an error.
Default Parameters
These have a fallback value, so the caller may omit them. They are useful when one value is common.
Typed Parameters
PHP allows type declarations such as string, int, float, array, and more. This improves reliability.
Variadic Parameters
Using ..., a function can accept an unknown number of arguments as an array-like list.
Pass by Value and Pass by Reference
By default, PHP passes values into a function copy-style. With &, you can allow the function to modify the original variable.
Step-by-Step Explanation
The basic syntax is function name(parameter1, parameter2) { ... }. Parameters are written inside parentheses after the function name. When calling the function, you provide matching arguments in the same order. A default parameter looks like $name = "Guest". A typed parameter looks like int $age. A reference parameter uses &$value. A variadic parameter uses ...$items and is usually placed last. Keep the order logical: required parameters first, optional ones after them.
Comprehensive Code Examples
Basic example
function greet($name) {
return "Hello, " . $name;
}
echo greet("Aisha");Real-world example
function calculateDiscount(float $price, float $percent = 10): float {
return $price - ($price * $percent / 100);
}
echo calculateDiscount(200);
echo "
";
echo calculateDiscount(200, 25);Advanced usage
function addTags(string $title, string ...$tags): array {
return [
"title" => $title,
"tags" => $tags
];
}
function increaseScore(int &$score, int $points): void {
$score += $points;
}
$post = addTags("PHP Basics", "functions", "parameters", "backend");
$score = 50;
increaseScore($score, 20);
print_r($post);
echo "
Score: " . $score;Common Mistakes
- Forgetting required arguments: calling a function without enough values causes an error. Fix: always match the required parameter list.
- Placing default parameters before required ones: this creates confusing function signatures. Fix: put required parameters first, optional ones last.
- Using the wrong type: passing a string where an
intis expected can break logic. Fix: validate input and use type declarations. - Changing variables unintentionally with references:
&modifies the original variable. Fix: use references only when truly needed.
Best Practices
- Use descriptive parameter names like
$productPriceinstead of vague names like$x. - Add type declarations whenever possible for safer and more readable code.
- Keep functions focused; if a function needs too many parameters, consider splitting responsibilities.
- Use default values for common optional behavior.
- Document expected parameter meaning clearly through naming and consistent ordering.
Practice Exercises
- Create a function called
multiplythat accepts two numbers as parameters and returns their product. - Create a function called
welcomeUserwith one required parameter for a username and one default parameter for a role. - Create a variadic function called
sumAllthat accepts any number of integers and returns the total.
Mini Project / Task
Build a small invoice helper function that accepts a product name, unit price, quantity, and an optional tax percentage, then returns the final total in a readable format.
Challenge (Optional)
Create a function that accepts an array of student marks and a passing score parameter, then returns only the marks that are greater than or equal to the passing score.
Detailed Introduction
A return value is the result a function sends back after finishing its work. In PHP, functions are often created to calculate something, transform data, validate input, or fetch a result. Instead of printing everything directly, a function can use return to hand a value back to the code that called it. This makes functions reusable, testable, and easier to combine with other logic. In real applications, return values are everywhere: a login checker may return true or false, a tax calculator may return a number, and a data formatter may return a string ready for display. Without return values, functions would be much less useful because they could perform actions but not provide results for later use.
Core Concepts & Sub-types
Single Value Returns
A function can return one value such as an integer, string, float, or boolean. This is the most common pattern.
Returning Arrays
If you need to send back multiple related values, you can return an array. This is useful when a function calculates several pieces of information at once.
Returning Null
A function may return null when no meaningful result exists. This can signal missing data or an unsuccessful lookup.
Early Returns
A function can return before reaching the end. This is helpful for validation, error handling, or stopping work once a result is known.
Step-by-Step Explanation
The basic syntax is simple: define a function, perform some logic, and use return followed by the value. Once PHP reaches return, the function stops executing immediately. The returned value can then be stored in a variable, echoed, passed into another function, or checked inside a condition. You may also declare a return type such as : int or : string to make your code clearer and safer. Beginners should remember that echo displays output, while return sends data back to the caller. They are not the same thing.
Comprehensive Code Examples
Basic example:
function add($a, $b) {
return $a + $b;
}
$total = add(5, 3);
echo $total;Real-world example:
function isEligibleForDiscount($age) {
return $age >= 60;
}
if (isEligibleForDiscount(65)) {
echo "Discount applied";
} else {
echo "No discount";
}Advanced usage:
function analyzeScore($score): array {
if ($score < 0 || $score > 100) {
return ['error' => 'Invalid score'];
}
$passed = $score >= 50;
$grade = $score >= 80 ? 'A' : ($score >= 60 ? 'B' : ($score >= 50 ? 'C' : 'F'));
return ['score' => $score, 'passed' => $passed, 'grade' => $grade];
}
$result = analyzeScore(72);
echo $result['grade'];Common Mistakes
- Using
echoinstead ofreturn: If you need the result later, return it rather than printing it immediately. - Forgetting that code stops after
return: Any statements after it in the same block will not run. - Not handling missing return paths: Make sure every logical branch returns an expected value, especially in conditional functions.
Best Practices
- Return values instead of mixing calculation and display logic.
- Use clear return types when possible to improve readability.
- Keep function behavior predictable so callers know what to expect.
- Use early returns to simplify nested conditions.
- Return structured arrays only when multiple related values are truly needed.
Practice Exercises
- Create a function called
squareNumber()that returns the square of a given number. - Write a function called
isEven()that returnstrueif a number is even andfalseotherwise. - Build a function called
formatFullName()that returns a full name by combining first and last name parameters.
Mini Project / Task
Build a PHP function called calculateFinalPrice() that accepts an item price and discount percentage, then returns the discounted total. Use the returned value to display a checkout message.
Challenge (Optional)
Create a function that accepts a student score and returns an array containing the original score, pass/fail status, and a letter grade. Then use the returned array to print a short report.
Detailed Introduction
Variable scope in PHP defines where a variable can be accessed and used in a script. It exists to keep code organized, predictable, and safer by limiting which parts of a program can read or change specific data. In real projects, scope matters when you build functions, reusable components, and applications with many files. For example, a shopping cart total inside a function should not accidentally overwrite a global site setting. Understanding scope helps you avoid bugs, write cleaner code, and control data flow properly. In PHP, the most common scope types are global, local, static, and parameter scope. There is also special access to superglobals, which are always available. If you do not understand scope early, your functions may fail to access needed values or may depend too heavily on outside variables, making code harder to test and maintain.
Core Concepts & Sub-types
Global Scope
A variable declared outside a function belongs to the global scope. It cannot be used directly inside a function unless you import it with global or access it through $GLOBALS.
Local Scope
A variable created inside a function exists only inside that function. Once the function ends, that variable is not available outside it.
Parameter Scope
Function parameters are local variables that receive values when the function is called. They exist only during that function execution.
Static Scope
A static variable inside a function keeps its value between function calls. It still remains local to that function, but it does not reset every time.
Superglobals
Special arrays like $_GET, $_POST, and $_SERVER are accessible from any scope without using global.
Step-by-Step Explanation
Start by declaring a variable outside a function: $siteName = "My Shop";. This is global. If you create a function and try to echo $siteName directly, PHP will not find it in local scope. To use it, write global $siteName; inside the function, or use $GLOBALS['siteName']. Next, declare a variable inside a function like $message = "Hello";; this is local and unavailable outside. Parameters work similarly: function greet($name) gives $name local function scope. For static variables, define one with static $count = 0;; each call remembers the previous value.
Comprehensive Code Examples
$x = 10;
function showValue() {
$y = 5;
echo $y;
}
showValue();Basic example: $y is local and works only inside the function.
$siteName = "PHP Store";
function displaySite() {
global $siteName;
echo "Welcome to " . $siteName;
}
displaySite();Real-world example: a function reads a global application setting.
function visitorCounter() {
static $count = 0;
$count++;
echo "Visitors counted in this request flow: " . $count . "
";
}
visitorCounter();
visitorCounter();
visitorCounter();Advanced usage: static variables preserve state across multiple function calls.
function calculateDiscount($price, $percent) {
$discount = $price * ($percent / 100);
return $price - $discount;
}
echo calculateDiscount(200, 15);This shows parameter scope and local calculation variables.
Common Mistakes
- Trying to use a global variable inside a function without
globalor$GLOBALS. Fix: pass values as parameters when possible, or explicitly import them. - Expecting a local variable to exist outside a function. Fix: return the value from the function and store it in another variable.
- Overusing global variables. Fix: prefer parameters and return values to keep functions reusable and easier to test.
- Forgetting that static variables keep previous values. Fix: use static only when persistent function-level state is intentional.
Best Practices
- Prefer passing data into functions through parameters instead of relying on globals.
- Keep variable names meaningful so their purpose is obvious within their scope.
- Use static variables sparingly and document why state must be preserved.
- Limit the use of
$GLOBALSbecause it makes code tightly coupled. - Write small functions with clear inputs and outputs for easier debugging.
Practice Exercises
- Create a global variable called
$appNameand display it inside a function usingglobal. - Write a function that accepts two parameters and returns their sum. Then try to access the internal sum variable outside the function and observe what happens.
- Create a function with a static variable that counts how many times the function is called.
Mini Project / Task
Build a simple page hit simulator with one function that uses a static counter to track calls, and another function that prints a global site title. Call both functions several times to see how local, global, and static scope behave together.
Challenge (Optional)
Create a small calculator script where all math functions receive values only through parameters and return results without using any global variables. Then compare it with a version that uses globals and identify which one is cleaner and easier to maintain.
Detailed Introduction
Arrays in PHP are data structures used to store multiple values inside a single variable. Instead of creating many separate variables like $item1, $item2, and $item3, you can group related data into one array. This makes your code cleaner, easier to manage, and much more scalable. Arrays exist because real applications constantly work with collections of data: product lists, user roles, menu items, API responses, form selections, and database records. In real life, arrays are used when displaying blog posts, looping through shopping cart items, storing configuration settings, or processing multiple form fields. PHP arrays are especially powerful because they can behave like indexed lists, key-value maps, and even nested structures. That flexibility makes them one of the most important topics in PHP. Once you understand arrays well, you can build dynamic pages, process user input efficiently, and prepare data for loops, functions, and databases.
Core Concepts & Sub-types
Indexed Arrays
Indexed arrays store values with numeric keys, starting from 0 by default. They are useful for ordered lists such as names, colors, or scores.
Associative Arrays
Associative arrays store values using custom string keys. They are useful when each value needs a meaningful label, such as name, email, or price.
Multidimensional Arrays
Multidimensional arrays contain other arrays inside them. They are commonly used for complex data like a list of users, products, or rows returned from a database query.
Step-by-Step Explanation
You create an array using square brackets like $items = ["Pen", "Book", "Bag"];. To access a value in an indexed array, use its position: $items[0]. For associative arrays, define key-value pairs like $user = ["name" => "Sara", "email" => "[email protected]"];. Access values with keys: $user["name"]. To add a new item to an indexed array, use $items[] = "Laptop";. To update a value, assign a new one to a key or index. Arrays are often processed using foreach, which is the easiest way to read each element one by one.
Comprehensive Code Examples
Basic example
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[0]; // Apple
$fruits[] = "Mango";
foreach ($fruits as $fruit) {
echo $fruit . "
";
}Real-world example
$product = [
"name" => "Keyboard",
"price" => 49.99,
"in_stock" => true
];
echo "Product: " . $product["name"] . "
";
echo "Price: $" . $product["price"];Advanced usage
$users = [
["name" => "Ali", "role" => "Admin"],
["name" => "Mina", "role" => "Editor"],
["name" => "John", "role" => "Subscriber"]
];
foreach ($users as $user) {
echo $user["name"] . " - " . $user["role"] . "
";
}Common Mistakes
- Using the wrong key or index, such as accessing
$items[3]when it does not exist. Fix: check array contents carefully or useisset()before access. - Confusing indexed and associative arrays. Fix: use numbers for positions and strings for named values consistently.
- Forgetting quotes around associative keys like
$user[name]. Fix: always write$user["name"].
Best Practices
- Use associative arrays when meaning matters, such as user data or settings.
- Choose clear variable names like
$productsor$customerData. - Use
foreachfor reading arrays because it is simpler and safer than manual indexing in many cases. - Check existence with
isset()orarray_key_exists()before reading uncertain keys.
Practice Exercises
- Create an indexed array of five city names and print the third city.
- Create an associative array for a student with keys for name, age, and grade, then print each value.
- Create a multidimensional array containing three products, each with name and price, then loop through and display them.
Mini Project / Task
Build a simple shopping cart array that stores three product names and prices, then loop through the cart and display each item with its price.
Challenge (Optional)
Create a multidimensional array of employees with name, department, and salary, then print only the employees who belong to the IT department.
Detailed Introduction
Indexed arrays in PHP are ordered collections of values stored under numeric positions called indexes. By default, PHP starts indexing at 0, so the first item is at position 0, the second at 1, and so on. They exist so developers can group related values together instead of creating many separate variables. In real applications, indexed arrays are used for storing lists such as product names, menu items, scores, tags, image paths, and rows of simple data. They are especially useful when the order of items matters and when you need to loop through values efficiently.
Core Concepts & Sub-types
Automatic Indexing
When you add values without specifying keys, PHP assigns numeric indexes automatically. This is the most common form of indexed arrays.
Manual Numeric Indexing
You can also assign numeric indexes yourself. This is helpful when you want to start from a custom position or replace a value at a specific index.
Multidimensional Indexed Arrays
An indexed array can contain other indexed arrays. This is useful for grouped lists such as student marks by subject or weekly sales figures.
Step-by-Step Explanation
To create an indexed array, use square brackets like $colors = ["red", "blue", "green"];. Each item is separated by a comma. To access a value, use its index: $colors[0] returns red. To update an item, assign a new value to an existing index: $colors[1] = "yellow";. To add a new item at the end, use empty brackets: $colors[] = "black";. To count items, use count($colors). To loop through items, use foreach for readability or for when you need the index position.
Comprehensive Code Examples
Basic Example
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[0];
echo $fruits[2];
?>Real-world Example
$tasks = ["Check email", "Attend meeting", "Write report"];
foreach ($tasks as $task) {
echo $task . "
";
}
?>Advanced Usage
$weeklySales = [
[120, 150, 180],
[200, 170, 160]
];
echo $weeklySales[0][1];
$weeklySales[1][] = 190;
for ($i = 0; $i < count($weeklySales[1]); $i++) {
echo $weeklySales[1][$i] . "
";
}
?>Common Mistakes
- Using the wrong index: Beginners often try
$array[1]for the first item. Remember indexes usually start at0. - Accessing missing positions: Reading
$array[10]when it does not exist causes warnings. Check withisset()first. - Mixing array types carelessly: Combining numeric and string keys can confuse beginners. Use indexed arrays only for ordered lists.
Best Practices
- Choose clear variable names such as
$studentsor$prices. - Use
foreachwhen you only need values and not positions. - Validate indexes with
isset()before accessing user-sensitive data. - Keep arrays focused on one kind of data to improve readability.
Practice Exercises
- Create an indexed array of five city names and print the third city.
- Create an array of four numbers and display all values using a
foreachloop. - Create an array of three hobbies, replace the second hobby, and print the updated list.
Mini Project / Task
Build a simple PHP script that stores a list of shopping items in an indexed array and prints each item on a new line with its position number.
Challenge (Optional)
Create an indexed array of exam scores, loop through it, calculate the total, and display the average score.
Detailed Introduction
Associative arrays in PHP are arrays that use named keys instead of numeric indexes. Rather than storing values at positions like 0, 1, and 2, associative arrays store values under meaningful labels such as name, email, or role. This makes data easier to read and manage, especially when working with structured information. In real applications, associative arrays are used for user profiles, configuration settings, database records, API responses, shopping cart items, and form data. They exist because many kinds of data are naturally described by labels, not positions. If you store a user record, it is much clearer to write $user['email'] than $user[2]. Associative arrays are one of the most important PHP features because they appear everywhere, from small scripts to full web applications.
Core Concepts & Sub-types
Key-Value Pairs
Each item has a key and a value. Example: 'name' => 'Alice'.
String Keys
Most associative arrays use string keys because they describe data clearly.
Mixed Arrays
PHP arrays can mix numeric and string keys, but beginners should keep structures consistent for clarity.
Multidimensional Associative Arrays
These are associative arrays containing other arrays, useful for grouped or nested data such as users, products, or settings.
Step-by-Step Explanation
To create an associative array, use square brackets and define items with the => operator. The left side is the key, and the right side is the value. Access a value by using its key inside brackets. Add or update values by assigning a new value to a key. Check whether a key exists before using it when data may be missing. Loop through associative arrays with foreach to access both keys and values. Basic syntax looks like this: create with $user = ['name' => 'Sara'];, read with $user['name'];, update with $user['name'] = 'Mina';, and loop with foreach ($user as $key => $value).
Comprehensive Code Examples
Basic Example
$student = [
'name' => 'John',
'age' => 21,
'course' => 'PHP'
];
echo $student['name'];
echo $student['course'];Real-world Example
$product = [
'id' => 101,
'title' => 'Mechanical Keyboard',
'price' => 89.99,
'in_stock' => true
];
if ($product['in_stock']) {
echo $product['title'] . ' costs $' . $product['price'];
}Advanced Usage
$users = [
[
'name' => 'Alice',
'email' => '[email protected]',
'role' => 'admin'
],
[
'name' => 'Bob',
'email' => '[email protected]',
'role' => 'editor'
]
];
foreach ($users as $user) {
echo $user['name'] . ' - ' . $user['role'] . '
';
}Common Mistakes
- Using the wrong key name, such as
'Name'instead of'name'. Keys are case-sensitive, so use consistent naming. - Accessing a missing key without checking. Use
isset()orarray_key_exists()when data may not exist. - Mixing numeric and string keys carelessly. Keep array structures predictable and readable.
- Forgetting quotes around string keys. Write
$user['email'], not$user[email].
Best Practices
- Use descriptive, lowercase keys like
first_nameoraccount_status. - Keep the same structure for similar records, especially in lists of users or products.
- Validate key existence before reading external or optional data.
- Use
foreachfor clean iteration over associative arrays. - Choose associative arrays when labels matter more than positions.
Practice Exercises
- Create an associative array for a book with keys for title, author, and year, then print each value.
- Build an associative array for a user profile and update one of the values after creation.
- Create a multidimensional associative array containing two products, then loop through it and print each product name and price.
Mini Project / Task
Build a simple profile card system using an associative array that stores a person's name, email, city, and occupation, then display the information in a readable format.
Challenge (Optional)
Create an associative array of student names and grades, then loop through it to print only the students who scored above 80.
Detailed Introduction
A multidimensional array in PHP is an array that contains one or more arrays inside it. Instead of storing a single flat list of values, it lets you organize related data into rows, groups, or nested structures. This exists because real applications often manage data that has levels, such as students and their grades, products and their details, or departments and their employees. In real life, multidimensional arrays are used in shopping carts, API responses, configuration files, dashboards, and database result sets. For example, when you fetch many users from a database, each user may be an associative array, and all users together form a multidimensional array. Learning this topic is important because it helps you model structured data clearly and access it efficiently in PHP programs.
Core Concepts & Sub-types
Indexed Multidimensional Arrays
These use numeric keys. They are useful for table-like data such as lists of scores or coordinates.
Associative Multidimensional Arrays
These use named keys like name, price, or email. They are common in real applications because they make data easier to read.
Mixed Multidimensional Arrays
PHP also allows a mix of indexed and associative arrays. For example, a list of products may use numeric outer keys and named inner keys.
Step-by-Step Explanation
To create a multidimensional array, define an outer array and place arrays inside it. You access nested values by chaining keys or indexes. For example, $users[0]['name'] means: get the first element from $users, then read its name value. You can loop through the outer array with foreach, then loop through inner arrays if needed. This is useful when printing reports, tables, or grouped data. You can also add new nested elements using bracket syntax, such as $products[] = ['name' => 'Mouse', 'price' => 25].
Comprehensive Code Examples
Basic example
$scores = [
[80, 90, 75],
[88, 76, 95],
[70, 85, 92]
];
echo $scores[1][2]; // 95
?>Real-world example
$products = [
['name' => 'Laptop', 'price' => 1200, 'stock' => 5],
['name' => 'Keyboard', 'price' => 45, 'stock' => 20],
['name' => 'Monitor', 'price' => 300, 'stock' => 8]
];
foreach ($products as $product) {
echo $product['name'] . ' - $' . $product['price'] . '
';
}
?>Advanced usage
$departments = [
'IT' => [
['name' => 'Sara', 'role' => 'Developer'],
['name' => 'Omar', 'role' => 'SysAdmin']
],
'HR' => [
['name' => 'Lina', 'role' => 'Recruiter']
]
];
foreach ($departments as $departmentName => $employees) {
echo '' . $departmentName . '
';
foreach ($employees as $employee) {
echo $employee['name'] . ' - ' . $employee['role'] . '
';
}
}
?>Common Mistakes
- Using the wrong index or key: Beginners often write
$products['name']instead of$products[0]['name']. Fix this by checking the exact structure first. - Assuming all inner arrays have the same keys: Missing keys can cause notices. Fix this by validating with
isset()before access. - Confusing outer and inner loops: Some learners print only the first level. Fix this by using nested
foreachwhen inner arrays must also be traversed.
Best Practices
- Use associative keys for meaningful real-world data.
- Keep array structures consistent across records.
- Name variables clearly, such as
$users,$user,$orders, and$order. - Use
print_r()orvar_dump()during debugging to inspect nested structures. - Prefer loops over hard-coded indexes when processing many records.
Practice Exercises
- Create a multidimensional array of three students, where each student has a name and age. Print every student name.
- Build a product list with name and price fields, then print only products that cost more than 50.
- Create a department array where each department contains employee names. Loop through all departments and print each employee.
Mini Project / Task
Build a simple class report using a multidimensional array. Store student names and three subject marks, then loop through the data and print each student with their total score.
Challenge (Optional)
Create a multidimensional array of orders, where each order contains customer information and a list of purchased items. Print the customer name and count how many items each order contains.
Detailed Introduction
Array functions in PHP are built-in tools that help you create, inspect, transform, search, sort, and combine arrays efficiently. Arrays are one of the most used data structures in PHP because they can store lists, mappings, configuration values, database results, and request data. Instead of manually looping through data for every small task, PHP provides array functions to reduce code, improve readability, and avoid bugs.
In real-life development, array functions are used when filtering products in an e-commerce app, sorting posts by date, extracting user names from database rows, removing duplicates from tags, or merging settings from multiple sources. They exist to make common operations faster and more expressive. Learning them is essential because modern PHP code relies heavily on array helpers for clean and maintainable logic.
Core Concepts & Sub-types
Inspection Functions
These help you examine arrays, such as count(), in_array(), array_key_exists(), and array_search().
Transformation Functions
These reshape data, such as array_map(), array_filter(), array_reduce(), array_values(), and array_keys().
Combination Functions
These join arrays together, such as array_merge(), array_combine(), and the spread operator in newer PHP code.
Sorting Functions
These arrange data, such as sort(), rsort(), asort(), ksort(), and usort().
Modification Functions
These add or remove elements, such as array_push(), array_pop(), array_shift(), array_unshift(), and unset().
Step-by-Step Explanation
Most array functions take an array as the first argument and then apply a specific operation. For example, count($items) returns the number of elements. in_array('apple', $fruits) checks whether a value exists. array_map(fn($x) => $x * 2, $numbers) loops internally and returns a new array. array_filter($numbers, fn($x) => $x > 10) keeps only matching values. sort($numbers) changes the original array directly, which is important to remember because not all functions return a new array. Beginners should always check whether a function mutates the array or returns a copy.
Comprehensive Code Examples
Basic example
$fruits = ['apple', 'banana', 'orange'];
echo count($fruits); // 3
if (in_array('banana', $fruits)) {
echo 'Found banana';
}
?>Real-world example
$products = [
['name' => 'Laptop', 'price' => 1200],
['name' => 'Mouse', 'price' => 25],
['name' => 'Keyboard', 'price' => 75]
];
$affordable = array_filter($products, function ($product) {
return $product['price'] < 100;
});
$names = array_map(function ($product) {
return $product['name'];
}, $affordable);
print_r($names);
?>Advanced usage
$orders = [
['total' => 50],
['total' => 120],
['total' => 30]
];
$grandTotal = array_reduce($orders, function ($carry, $order) {
return $carry + $order['total'];
}, 0);
echo $grandTotal; // 200
?>Common Mistakes
- Confusing mutated arrays with returned arrays:
sort()changes the original array, whilearray_map()returns a new one. - Forgetting strict checks: use
in_array($value, $array, true)when type matters. - Using the wrong sort function:
sort()resets keys, whileasort()preserves them.
Best Practices
- Prefer expressive functions like
array_filter()andarray_map()for readable code. - Use strict mode in search functions when comparing strings, numbers, or booleans.
- Choose key-preserving functions carefully when working with associative arrays.
- Keep callbacks small and focused for maintainability.
Practice Exercises
- Create an array of five numbers and use an array function to count them.
- Make an array of names and check whether a specific name exists.
- Build an array of prices and create a new array containing only prices above 50.
Mini Project / Task
Create a product list array, filter products under a chosen budget, extract their names, and sort the final list alphabetically.
Challenge (Optional)
Given an array of student records, calculate the total of all grades, keep only students with grades above 70, and return a sorted list of their names.
Detailed Introduction
In PHP, a string is a sequence of characters used to store and manipulate text. Strings are everywhere in real applications: usernames, email addresses, article titles, search queries, messages, file paths, and HTML output are all handled as strings. PHP provides rich string features because web development constantly works with user input and textual content. You will use strings when printing content, validating forms, building URLs, formatting templates, and processing data from databases or APIs. Understanding strings well is essential because small mistakes with quotes, concatenation, escaping, or interpolation can cause bugs, broken output, or security issues.
Core Concepts & Sub-types
Single-Quoted Strings
Single quotes treat most characters literally. Variables are not expanded inside them. Use them when you want exact text.
Double-Quoted Strings
Double quotes allow variable interpolation and special escaped characters like \n and \t. They are useful when building readable output.
Concatenation
PHP joins strings using the dot operator .. This is common when combining labels, variables, and dynamic content.
String Functions
PHP includes built-in helpers such as strlen(), strtolower(), strtoupper(), trim(), strpos(), and str_replace() for measuring, transforming, searching, and editing text.
Step-by-Step Explanation
To create a string, assign text to a variable using quotes. Example: $name = "Alice";. To display it, use echo $name;. To combine strings, write "Hello, " . $name. If using double quotes, PHP can insert variables directly, like "Hello, $name". To find length, use strlen($name). To clean spaces from input, use trim($input). To check if text contains another piece of text, use strpos($email, "@"). If you need to replace content, use str_replace("old", "new", $text). Beginners should start by creating simple strings, printing them, combining them, then using functions to inspect or transform them.
Comprehensive Code Examples
Basic example:
$firstName = "John";
$lastName = 'Doe';
echo "Hello, $firstName";
echo "
";
echo $firstName . " " . $lastName;
?>Real-world example:
$email = " [email protected] ";
$cleanEmail = trim(strtolower($email));
if (strpos($cleanEmail, "@") !== false) {
echo "Valid email format: " . $cleanEmail;
} else {
echo "Invalid email format";
}
?>Advanced usage:
$product = "Laptop";
$price = 1200;
$message = "Product: $product";
$message .= "
Price: $" . number_format($price, 2);
$message = str_replace("Laptop", "Gaming Laptop", $message);
echo $message;
echo "
Message length: " . strlen($message);
?>Common Mistakes
- Using single quotes when expecting variables to expand:
'Hello $name'prints the variable name literally. Use double quotes or concatenation. - Forgetting the dot operator: Writing
"Hello" $namecauses an error. Use"Hello " . $name. - Misreading
strpos()results: If the text starts at position 0, it is still valid. Always compare with!== false.
Best Practices
- Use single quotes for plain static text and double quotes when interpolation improves readability.
- Sanitize and normalize user input with functions like
trim()andstrtolower()when needed. - Prefer clear, readable string building over overly complex nested expressions.
- Use built-in PHP string functions instead of writing custom logic for common operations.
Practice Exercises
- Create two string variables for first name and city, then print a greeting sentence using both.
- Ask the user for a word, then display its length in characters using a PHP string function.
- Create a sentence with extra spaces at the beginning and end, then remove them and print the cleaned version.
Mini Project / Task
Build a simple profile formatter that stores a user's name, email, and country as strings, cleans the values, and prints them in a neat HTML-style summary.
Challenge (Optional)
Create a PHP script that takes a sentence, converts it to lowercase, replaces one chosen word with another, and shows both the original and updated versions.
Detailed Introduction
String functions in PHP are built-in tools used to create, read, search, clean, format, split, and transform text. A string is any sequence of characters such as a name, email, password, URL, sentence, or file path. In real applications, developers constantly work with strings when validating form input, generating slugs, formatting messages, cleaning user data, extracting keywords, and preparing content for display or storage. PHP includes many string functions because text processing is one of the most common backend tasks. Learning them helps you write shorter, clearer, and more reliable code instead of manually looping through characters for every operation.
Core Concepts & Sub-types
Length and inspection
Functions like strlen() measure string size, while str_contains(), strpos(), and substr() help inspect and locate text.
Modification and formatting
strtolower(), strtoupper(), ucfirst(), ucwords(), and trim() change the appearance or cleanliness of strings.
Replacement and splitting
str_replace() swaps text, while explode() splits a string into an array and implode() joins array values back into a string.
Comparison
strcmp() and direct equality checks are used when comparing text values exactly.
Step-by-Step Explanation
Most PHP string functions follow a simple pattern: the function name comes first, then the string value is passed inside parentheses. Example: strlen($text) returns the number of characters in $text. Some functions need more arguments. For example, str_replace("old", "new", $text) replaces matching text inside the original string. substr($text, 0, 5) starts from index 0 and returns 5 characters. explode(",", $tags) breaks a comma-separated string into pieces. Always store the result if the function returns a changed string, because many string functions do not modify the original variable automatically.
Comprehensive Code Examples
$name = " john doe ";br$cleanName = trim($name);br echo strlen($cleanName); // 8br echo strtoupper($cleanName); // JOHN DOE$email = "[email protected]";br $normalizedEmail = strtolower(trim($email));br if (str_contains($normalizedEmail, "@example.com")) {br echo "Company email detected";br }$title = "Learn PHP String Functions Fast";br $slug = strtolower(str_replace(" ", "-", $title));br echo $slug; // learn-php-string-functions-fastbrbr $tags = "php,strings,backend";br $tagArray = explode(",", $tags);br echo implode(" | ", $tagArray); // php | strings | backendbrbr $message = "Order-2024-Complete";br echo substr($message, 0, 5); // OrderCommon Mistakes
- Forgetting to save returned values:
trim($text)does not permanently change$textunless you reassign it. - Misusing
strpos(): position0is valid, so check with!== falseinstead of a loose condition. - Ignoring case differences: "PHP" and "php" are not always equal; normalize with
strtolower()when needed.
Best Practices
- Trim and normalize user input before validation or storage.
- Use built-in string functions instead of manual character handling whenever possible.
- Choose clear variable names like
$cleanTitleor$normalizedEmailto show transformation steps. - Test edge cases such as empty strings, extra spaces, and missing separators.
Practice Exercises
- Create a string containing a full name with extra spaces, then remove the spaces and print the cleaned result and its length.
- Write code that converts a sentence to lowercase and replaces all spaces with hyphens.
- Take a comma-separated list of fruits, split it into an array, and print the items joined with
/.
Mini Project / Task
Build a simple username formatter that accepts a full name, removes extra spaces, converts it to lowercase, replaces spaces with underscores, and prints the final username.
Challenge (Optional)
Create a short slug generator for blog titles that trims spaces, converts text to lowercase, replaces spaces with hyphens, and removes a chosen special character such as ! or ?.
Detailed Introduction
PHP forms are one of the most important features in web development because they allow websites to collect data from users and send it to the server for processing. In real applications, forms are used for login pages, registration systems, contact forms, search boxes, checkout pages, file uploads, and feedback forms. HTML creates the visible form fields, while PHP reads the submitted values, validates them, and performs actions such as saving data, sending emails, or displaying results. Without forms, a website would be mostly static and unable to interact with users in meaningful ways. PHP supports form handling through special superglobal arrays like $_GET, $_POST, and $_SERVER. Understanding forms is essential because this topic connects front-end input with back-end logic, making it a foundation for building dynamic web applications.
Core Concepts & Sub-types
GET Forms
GET sends form data through the URL. It is useful for search forms, filters, and actions where bookmarking or sharing the URL is helpful.
POST Forms
POST sends data in the request body. It is better for sensitive or larger data such as passwords, registration details, and message forms.
Form Action and Method
The action attribute tells the form where to send data, and the method attribute defines how it is sent.
Validation and Sanitization
Validation checks whether input is correct, while sanitization cleans input to make it safe for output or storage.
Step-by-Step Explanation
First, create an HTML form using <form>. Add inputs with a name attribute because PHP reads submitted values by these names. Choose method="post" or method="get". In PHP, check whether the form was submitted by examining $_SERVER['REQUEST_METHOD']. Then read the submitted fields from $_POST or $_GET. Next, validate the values, sanitize them when needed, and finally process them. For safe output in HTML, use htmlspecialchars() to prevent cross-site scripting issues.
Comprehensive Code Examples
Basic Example
<form method="post" action="">
<input type="text" name="username" placeholder="Enter name">
<button type="submit">Send</button>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = htmlspecialchars($_POST['username']);
echo "Hello, " . $username;
}
?>Real-world Example
<form method="post" action="">
<input type="email" name="email" placeholder="Email">
<textarea name="message" placeholder="Your message"></textarea>
<button type="submit">Contact Us</button>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = htmlspecialchars(trim($_POST['message']));
if ($email && !empty($message)) {
echo "Form submitted successfully.";
} else {
echo "Please enter a valid email and message.";
}
}
?>Advanced usage
<?php
$errors = [];
$name = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
if ($name === '') {
$errors[] = 'Name is required.';
}
if (empty($errors)) {
echo "Saved: " . htmlspecialchars($name);
}
}
?>
<form method="post" action="">
<input type="text" name="name" value="<?= htmlspecialchars($name) ?>">
<button type="submit">Save</button>
</form>Common Mistakes
- Missing name attributes: inputs without
nameare not submitted. Add proper names to every field. - Using GET for sensitive data: passwords should not appear in URLs. Use
POSTinstead. - Printing raw user input: this can create security issues. Escape output with
htmlspecialchars(). - Skipping validation: never assume user input is correct. Always validate required fields and formats.
Best Practices
- Use
POSTfor forms that modify data or include private information. - Validate on the server even if client-side validation exists.
- Sanitize output before displaying user data in HTML.
- Preserve submitted values after errors so users do not retype everything.
- Use clear error messages to improve usability.
Practice Exercises
- Create a form with a name field and display a greeting after submission.
- Build a form with email and age fields, then validate that email is valid and age is numeric.
- Create a feedback form that shows an error when the message field is empty.
Mini Project / Task
Build a simple contact form that accepts name, email, and message, validates all fields, and displays either success or field-specific error messages.
Challenge (Optional)
Extend your contact form so that previously entered values remain in the form after validation fails, while keeping the output safe from XSS.
Detailed Introduction
The GET method is an HTTP request method used to send small pieces of data from the browser to the server through the URL. In PHP, it is commonly accessed with the $_GET superglobal array. You see GET requests every day in search pages, filters, pagination links, product sorting, and profile pages where values are included after a question mark in the URL, such as page.php?name=Ali&age=20. GET exists because many web interactions are simple requests for data rather than private submissions. It is useful when users need to bookmark, share, or revisit a URL with the same parameters. Because GET data is visible in the address bar, it should never be used for passwords or sensitive information. In real projects, developers use GET for search forms, category filters, article IDs, and navigation options because it makes requests readable, linkable, and easy to debug.
Core Concepts & Sub-types
Query Parameters
These are key-value pairs in the URL, such as ?category=php&sort=asc.
Reading with $_GET
PHP stores URL parameters inside the associative array $_GET so you can read values by name.
GET Forms
When an HTML form uses method='GET', its input values are appended to the URL after submission.
Validation and Defaults
Because parameters may be missing or invalid, you should check with isset(), null coalescing, and sanitization functions.
Step-by-Step Explanation
First, a browser sends a request to a PHP page. If the URL includes query parameters, PHP fills the $_GET array automatically. For example, in product.php?id=5, the key is id and the value is 5. You can read it using $_GET['id']. Since a key may not exist, beginners should safely read it using $id = $_GET['id'] ?? null;. If the value is expected to be a number, convert or validate it before using it. For text input, sanitize it before output to avoid security issues. When building forms, use <form method='GET'> so form values appear in the URL and can be shared easily.
Comprehensive Code Examples
Basic example:
<?php
$name = $_GET['name'] ?? 'Guest';
echo "Hello, " . htmlspecialchars($name);
?>Real-world example:
<form method="GET">
<input type="text" name="search" placeholder="Search courses">
<button type="submit">Search</button>
</form>
<?php
$search = $_GET['search'] ?? '';
if ($search !== '') {
echo "You searched for: " . htmlspecialchars($search);
}
?>Advanced usage:
<?php
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
$sort = $_GET['sort'] ?? 'asc';
if ($page === false || $page === null) {
$page = 1;
}
$allowedSort = ['asc', 'desc'];
if (!in_array($sort, $allowedSort, true)) {
$sort = 'asc';
}
echo "Page: " . $page . "<br>";
echo "Sort: " . htmlspecialchars($sort);
?>Common Mistakes
- Using GET for sensitive data: Never send passwords or private details in the URL.
- Accessing missing keys directly: Use
isset()or??to avoid warnings. - Printing raw user input: Use
htmlspecialchars()before outputting text. - Assuming values are valid: Validate numbers, allowed options, and required fields.
Best Practices
- Use GET for reading, filtering, searching, and navigation.
- Keep parameter names short but meaningful, like
pageorcategory. - Always sanitize output and validate expected types.
- Provide default values when parameters are missing.
- Use GET URLs to make pages bookmarkable and shareable.
Practice Exercises
- Create a PHP page that reads a
nameparameter from the URL and displays a greeting. - Build a GET form that accepts a city name and prints it after submission.
- Create a page that reads
pagefrom the URL and showsCurrent page: Xwith a default of 1.
Mini Project / Task
Build a course search page with a GET form that accepts a keyword and a sort option, then displays the selected values safely on the screen.
Challenge (Optional)
Create a product listing page that accepts category, page, and sort through GET, validates all three inputs, and displays clean fallback values when any parameter is missing or invalid.
Detailed Introduction
The POST method is an HTTP request method used to send data from the browser to the server. In PHP, it is most commonly used when submitting forms that create, update, or process sensitive information such as login details, registration forms, comments, checkout forms, and profile updates. Unlike GET, which appends data to the URL, POST sends data inside the request body. This makes it better for larger payloads and more appropriate for private or sensitive values. In real applications, POST is used when a user submits a contact form, logs into a dashboard, uploads data, or saves settings. PHP exposes submitted POST values through the $_POST superglobal array, allowing developers to retrieve form fields by name and process them on the server. Understanding POST is essential because nearly every dynamic web application depends on receiving and validating user input safely.
Core Concepts & Sub-types
HTML Form with POST
A form uses method="post" to tell the browser to send values as a POST request when the user submits it.
PHP $_POST
The $_POST array stores submitted form data as key-value pairs. Each input field name becomes an array key.
Request Method Checking
Developers often check $_SERVER['REQUEST_METHOD'] to confirm that the page was submitted with POST before processing data.
Validation and Sanitization
POST data should never be trusted directly. Always validate required fields, expected formats, and sanitize output before displaying it.
Step-by-Step Explanation
First, create an HTML form. Second, give inputs a name attribute because PHP reads submitted values by name. Third, set the form method to POST. Fourth, in the PHP file, check whether the request method is POST. Fifth, read values from $_POST. Finally, validate, process, and safely output results. For example, if a text input has name="username", then PHP can access it with $_POST['username']. If the form is not submitted yet, trying to access missing keys may cause warnings, so use isset() or the null coalescing operator.
Comprehensive Code Examples
Basic example
<form method="post">
<input type="text" name="name" placeholder="Enter your name">
<button type="submit">Send</button>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name'] ?? '';
echo "Hello, " . htmlspecialchars($name);
}
?>Real-world example
<form method="post">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
if ($email === '' || $password === '') {
echo "All fields are required.";
} else {
echo "Login form received for: " . htmlspecialchars($email);
}
}
?>Advanced usage
<?php
$errors = [];
$username = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = trim($_POST['username'] ?? '');
if ($username === '') {
$errors[] = 'Username is required.';
} elseif (strlen($username) < 3) {
$errors[] = 'Username must be at least 3 characters.';
}
if (!$errors) {
echo "Saved user: " . htmlspecialchars($username);
}
}
?>
<form method="post">
<input type="text" name="username" value="<?= htmlspecialchars($username) ?>">
<button type="submit">Save</button>
</form>Common Mistakes
- Forgetting the name attribute: inputs without
nameare not sent in POST data. - Accessing $_POST directly without checks: use
isset()or??to avoid undefined index warnings. - Displaying raw user input: always use
htmlspecialchars()before outputting submitted values. - Skipping validation: never assume the browser sent valid data.
Best Practices
- Check
$_SERVER['REQUEST_METHOD'] === 'POST'before processing. - Validate required fields, length, and format on the server side.
- Escape all user-facing output with
htmlspecialchars(). - Use POST for actions that change data, such as creating or updating records.
- Keep form handling code organized by separating validation and output logic.
Practice Exercises
- Create a form with one text field called
cityand display the submitted city using POST. - Build a form with
emailandagefields, then show an error if either is empty. - Create a feedback form with a textarea and print the message safely after submission.
Mini Project / Task
Build a simple registration form that accepts username, email, and password, checks that all fields are filled, and prints a success message if validation passes.
Challenge (Optional)
Extend the registration form so it preserves old form values after invalid submission and shows a list of validation errors above the form.
Detailed Introduction
Form validation is the process of checking user input before accepting, storing, or processing it. In PHP, validation is essential because web forms collect data from real users, and that data can be incomplete, incorrectly formatted, or even malicious. For example, a registration form may require a valid email, a strong password, and a non-empty username. Without validation, bad data can enter your application, cause errors, break business logic, or create security risks. In real life, form validation is used in login pages, checkout forms, contact forms, job applications, and admin dashboards. Good validation improves user experience by showing clear errors and protects your system by ensuring the submitted values match expected rules.
Core Concepts & Sub-types
Required Validation
Checks whether a field has a value. Common for name, email, and password fields.
Format Validation
Ensures data follows a valid pattern, such as email format, URL format, or numeric input.
Length Validation
Restricts minimum or maximum characters, useful for usernames, passwords, and comments.
Type Validation
Confirms that a value is an integer, float, boolean, or array when expected.
Custom Validation
Applies business rules, such as matching password confirmation or allowing only specific age ranges.
Step-by-Step Explanation
In PHP, validation usually begins after checking the request method with $_SERVER['REQUEST_METHOD']. Then you read submitted values from $_POST, clean them with functions like trim(), and test them with conditions or filter functions. Errors are often stored in an array so you can display all messages at once. A typical flow is: receive data, sanitize basic whitespace, validate each field, store errors, and continue only if the errors array is empty. PHP provides useful tools such as empty(), strlen(), filter_var(), and preg_match().
Comprehensive Code Examples
Basic example:
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
if ($name === '') {
$errors['name'] = 'Name is required.';
}
}
?>Real-world example:
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = trim($_POST['email'] ?? '');
$password = trim($_POST['password'] ?? '');
if ($email === '') {
$errors['email'] = 'Email is required.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Enter a valid email address.';
}
if ($password === '') {
$errors['password'] = 'Password is required.';
} elseif (strlen($password) < 8) {
$errors['password'] = 'Password must be at least 8 characters.';
}
if (empty($errors)) {
echo 'Form submitted successfully.';
}
}
?>Advanced usage:
function validateRegistration(array $data): array {
$errors = [];
$username = trim($data['username'] ?? '');
$email = trim($data['email'] ?? '');
$age = $data['age'] ?? '';
if ($username === '' || strlen($username) < 3) {
$errors['username'] = 'Username must be at least 3 characters.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Invalid email format.';
}
if (!filter_var($age, FILTER_VALIDATE_INT) || $age < 18) {
$errors['age'] = 'You must be at least 18.';
}
return $errors;
}
?>Common Mistakes
- Trusting client-side validation only: Always validate again in PHP because browser checks can be bypassed.
- Using
empty()carelessly: The value0may be treated as empty. Use stricter checks when needed. - Not trimming input: Spaces can make valid-looking fields fail. Use
trim()before validation.
Best Practices
- Validate on the server for every important field.
- Store errors in an associative array by field name.
- Show clear, user-friendly error messages.
- Use built-in filters like
filter_var()where possible. - Separate validation logic into functions for reuse and cleaner code.
Practice Exercises
- Create a form that requires a full name and shows an error if left blank.
- Build an email form that rejects invalid email formats.
- Add password validation that requires at least 8 characters.
Mini Project / Task
Build a user registration form that validates username, email, password, and age, then displays all field-specific error messages.
Challenge (Optional)
Create a validation function that checks password confirmation, ensures age is numeric, and blocks usernames containing spaces.
Detailed Introduction
PHP sessions are a built-in way to store user-specific data on the server across multiple page requests. Since HTTP is stateless, a web server does not naturally remember who a visitor is after one page loads. Sessions solve this by assigning each visitor a unique session ID, usually stored in a cookie, while the actual data lives on the server. In real applications, sessions are used for login systems, shopping carts, flash messages, multi-step forms, role-based dashboards, and temporary user preferences. Sessions are safer than storing sensitive data directly in cookies because the server keeps the values. A browser only keeps the session identifier. This makes sessions a core part of nearly every dynamic PHP web application.
Core Concepts & Sub-types
session_start()
This function starts or resumes a session. It must be called before output is sent to the browser so PHP can manage the session cookie correctly.
$_SESSION
This superglobal array stores session data as key-value pairs. You can save usernames, user IDs, cart items, or status flags here.
Session ID
Each user gets a unique identifier that connects their browser to server-side session data.
session_unset() and session_destroy()
These are used to remove session data and fully end a session, commonly during logout.
Session Regeneration
session_regenerate_id(true) creates a fresh session ID, reducing session fixation risks after login.
Step-by-Step Explanation
First, call session_start() at the top of the PHP file. Next, write values into $_SESSION like a normal associative array. Then, read those values on another page after starting the session again. To remove a single value, use unset($_SESSION['key']). To clear everything, use session_unset() and session_destroy(). Remember that every page using session data must start the session first.
Comprehensive Code Examples
Basic example
<?php
session_start();
$_SESSION['name'] = 'Alice';
echo 'Session created.';<?php
session_start();
echo $_SESSION['name'] ?? 'No name stored.';Real-world example
<?php
session_start();
$username = 'admin';
$password = 'secret123';
if ($username === 'admin' && $password === 'secret123') {
session_regenerate_id(true);
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $username;
echo 'Login successful';
} else {
echo 'Invalid credentials';
}<?php
session_start();
if (!isset($_SESSION['logged_in'])) {
echo 'Access denied';
exit;
}
echo 'Welcome, ' . $_SESSION['username'];Advanced usage
<?php
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
$_SESSION['cart'][] = [
'product' => 'Keyboard',
'qty' => 2
];
foreach ($_SESSION['cart'] as $item) {
echo $item['product'] . ' x ' . $item['qty'] . '<br>';
}Common Mistakes
- Calling
session_start()after HTML output. Fix: place it at the very top before any echo or markup. - Forgetting to start the session on pages that read data. Fix: call
session_start()on every session-dependent page. - Storing sensitive raw data like passwords in
$_SESSION. Fix: store only necessary identifiers or safe metadata. - Not destroying sessions on logout. Fix: use
session_unset()andsession_destroy().
Best Practices
- Regenerate the session ID after login or privilege changes.
- Store minimal data in the session to keep applications efficient.
- Validate that expected session keys exist before using them.
- Use sessions for temporary state, not permanent storage.
- Implement proper logout that clears all session data securely.
Practice Exercises
- Create one page that stores a favorite color in
$_SESSIONand another page that displays it. - Build a page counter that increases a session value every time the page is refreshed.
- Make a login simulation that stores a username in the session and shows a welcome message on a dashboard page.
Mini Project / Task
Build a simple shopping cart session system where a user can add product names to $_SESSION['cart'] and view the cart contents on another page.
Challenge (Optional)
Create a multi-step form that saves each step in the session and shows a final summary page only when all required steps are completed.
Detailed Introduction
PHP cookies are small pieces of data stored in a userās browser by a website. They exist so a web application can remember information between page requests, because HTTP is stateless by default. In real life, cookies are used for language preferences, dark mode settings, remembering a username, analytics identifiers, shopping cart support, and login persistence. In PHP, cookies are created on the server using setcookie(), then sent as HTTP headers to the browser. On later requests, the browser returns matching cookies back to the server, where PHP makes them available through the $_COOKIE superglobal. Cookies are useful when you want lightweight client-side persistence, but they should never store sensitive data such as passwords or private personal information in plain text.
Core Concepts & Sub-types
Session Cookies
These last only until the browser is closed. They are created without a future expiration time.
Persistent Cookies
These remain available until a defined expiration time. They are useful for preferences like theme selection or remembered usernames.
Secure and HttpOnly Cookies
Secure cookies are sent only over HTTPS. HttpOnly cookies cannot be accessed by JavaScript, which helps reduce some XSS risks. Modern apps often combine both.
SameSite Cookies
SameSite controls whether cookies are sent with cross-site requests. Common values are Lax, Strict, and None.
Step-by-Step Explanation
To create a cookie, call setcookie() before any HTML output. A simple form is setcookie(name, value, expire, path, domain, secure, httponly). The name is the cookie key, value is the stored data, and expire is a Unix timestamp. If you omit the expiration, it becomes a session cookie. After the browser receives it, future requests include the cookie, and you can read it from $_COOKIE['name']. To delete a cookie, set it again with an expiration time in the past. Remember: cookies set during the current request usually appear in the browser on the next request, not instantly in the current page load unless you also assign a local value manually.
Comprehensive Code Examples
Basic Example
<?php
setcookie('username', 'Alex', time() + 3600, '/');
echo 'Cookie has been set.';
?>Real-world Example
<?php
if (isset($_POST['theme'])) {
setcookie('theme', $_POST['theme'], time() + 86400 * 30, '/');
}
$theme = $_COOKIE['theme'] ?? 'light';
echo 'Current theme: ' . htmlspecialchars($theme);
?>Advanced Usage
<?php
setcookie('remember_user', '42', [
'expires' => time() + 604800,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
if (isset($_COOKIE['remember_user'])) {
echo 'Returning user ID: ' . (int) $_COOKIE['remember_user'];
}
?>Common Mistakes
- Sending output before
setcookie(): Fix by setting cookies before any echo or HTML. - Storing sensitive data directly: Fix by storing only safe identifiers, not passwords or private details.
- Expecting immediate availability in
$_COOKIE: Fix by understanding the browser returns cookies on the next request. - Forgetting security flags: Fix by using
secure,httponly, andsamesitewhen appropriate.
Best Practices
- Use cookies for small, non-sensitive data only.
- Prefer HTTPS and enable the
secureflag in production. - Use
HttpOnlyfor cookies that do not need JavaScript access. - Validate and sanitize cookie values before using them.
- Set reasonable expiration times and delete outdated cookies properly.
Practice Exercises
- Create a cookie named
citythat stores a userās favorite city for 1 hour and display it on the next request. - Build a page that saves a preferred language in a cookie and shows the selected language when the page reloads.
- Write code to delete a cookie named
promo_codeand confirm whether it still exists.
Mini Project / Task
Build a āRemember My Themeā feature where a user chooses light or dark mode, the choice is stored in a cookie for 30 days, and the page loads using that saved preference.
Challenge (Optional)
Create a visit counter using cookies that increases each time the user reloads the page and resets automatically after 24 hours.
Detailed Introduction
PHP file handling is the process of creating, reading, writing, appending, renaming, and deleting files on a server. It exists because web applications often need to store or retrieve data outside a database, such as logs, configuration files, uploaded documents, cache files, CSV exports, and simple text content. In real life, file handling is used in systems that save contact form submissions to logs, generate reports, upload images, or store temporary session-like data. Learning file handling helps you understand how PHP interacts with the operating system and gives you control over persistent data in small and medium-sized tasks.
Core Concepts & Sub-types
Reading Files
Used to open and fetch file content with functions like fopen(), fgets(), fread(), and file_get_contents().
Writing Files
Used to create or overwrite files with fwrite() or file_put_contents().
Appending Files
Adds new content to the end of an existing file without removing old content, commonly used for logs.
File Modes
Modes control how a file is opened: r for read, w for write and truncate, a for append, and x for create-only.
File Checks
Functions like file_exists(), is_readable(), and is_writable() help prevent runtime errors.
Step-by-Step Explanation
To work with a file manually, first choose a path such as data.txt. Next, open the file using fopen($file, $mode). This returns a file handle resource. Then perform an action: read with fgets() or fread(), or write with fwrite(). Finally, close the file using fclose(). For simpler tasks, PHP provides shortcuts: file_get_contents() reads an entire file as a string, and file_put_contents() writes content in one call.
Comprehensive Code Examples
Basic example:
<?php
$content = "Hello, PHP file handling!";
file_put_contents("note.txt", $content);
echo file_get_contents("note.txt");
?>Real-world example:
<?php
$logFile = "app.log";
$message = "User visited at " . date("Y-m-d H:i:s") . PHP_EOL;
file_put_contents($logFile, $message, FILE_APPEND);
echo "Visit logged successfully.";
?>Advanced usage:
<?php
$file = "users.csv";
if (file_exists($file) && is_readable($file)) {
$handle = fopen($file, "r");
while (($row = fgetcsv($handle)) !== false) {
echo "Name: " . $row[0] . ", Email: " . $row[1] . "<br>";
}
fclose($handle);
} else {
echo "File not available.";
}
?>Common Mistakes
Using
wmode accidentally deletes existing content. Fix: useafor appending when needed.Forgetting to close files after
fopen(). Fix: always callfclose()after finishing.Reading files without checking existence or permissions. Fix: use
file_exists()andis_readable()first.
Best Practices
Prefer
file_get_contents()andfile_put_contents()for simple operations.Store files in dedicated folders like
storage/orlogs/for organization.Validate file paths and avoid using unchecked user input in file operations for security.
Use append mode for logs and backup important files before overwriting.
Practice Exercises
Create a file named
welcome.txtand write a short message into it, then display the content in the browser.Build a script that appends the current date and time to a file named
history.txteach time the script runs.Write a program that checks whether
notes.txtexists before trying to read it, then shows an error message if it does not.
Mini Project / Task
Build a simple visitor logger that stores each page visit in a text file with the visitor time and IP address.
Challenge (Optional)
Create a PHP script that reads a CSV file of products and prints each product in a formatted HTML list while safely handling missing files or empty rows.
Detailed Introduction
Reading files in PHP means loading data stored in a file so your script can display, process, search, or transform it. This is important because many applications rely on text files, CSV exports, logs, configuration files, and uploaded content. In real life, developers read files to show reports, import product data, parse server logs, load templates, or process simple local storage before moving to databases. PHP provides multiple ways to read files depending on whether you want the whole file at once, one line at a time, or character-by-character. Choosing the right method affects memory usage, speed, and code clarity. Beginners often start with small files, but professional developers must also think about missing files, permissions, file size, and secure paths.
Core Concepts & Sub-types
file_get_contents()
Reads an entire file into a string. It is the simplest option for small to medium files.
file()
Reads a file into an array where each line becomes an array item. Useful for line-based processing.
fopen() with fread()
Opens a file handle, then reads a specific number of bytes. Good when you need more control.
fopen() with fgets()
Reads one line at a time. Ideal for large files because it uses less memory.
feof()
Checks whether the file pointer has reached the end of the file, often used in loops with fgets().
Step-by-Step Explanation
To read a file, first identify the path such as data/example.txt. For simple full reads, use file_get_contents('data/example.txt'). For controlled reading, open the file using fopen('data/example.txt', 'r'), where r means read-only mode. Then read content using fread() or fgets(). Always check whether the file exists before reading, and close file handles with fclose(). When reading line by line, use a loop until feof() becomes true. This approach is safer for large files because PHP does not load the whole file into memory at once.
Comprehensive Code Examples
Basic example
if (file_exists('notes.txt')) {
$content = file_get_contents('notes.txt');
echo $content;
} else {
echo 'File not found.';
}
?>Real-world example
$path = 'logs/app.log';
if (!file_exists($path)) {
die('Log file missing.');
}
$lines = file($path);
foreach ($lines as $line) {
if (strpos($line, 'ERROR') !== false) {
echo $line . '
';
}
}
?>Advanced usage
$path = 'large-data.txt';
if (!is_readable($path)) {
die('File is not readable.');
}
$handle = fopen($path, 'r');
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle);
if ($line !== false) {
echo htmlspecialchars(trim($line)) . '
';
}
}
fclose($handle);
}
?>Common Mistakes
- Not checking if a file exists: This causes warnings. Fix it with
file_exists()oris_readable(). - Reading huge files with file_get_contents(): This can consume too much memory. Use
fgets()line by line instead. - Forgetting to close a file handle: Open handles should be closed with
fclose(). - Using unsafe output: File content may contain HTML. Escape output with
htmlspecialchars().
Best Practices
- Use relative paths carefully and keep files in predictable folders.
- Prefer
is_readable()when permissions might be an issue. - Use
file_get_contents()for simple small files andfgets()for large ones. - Always validate and sanitize displayed content.
- Handle missing files gracefully with friendly error messages.
Practice Exercises
- Create a PHP script that reads a text file and prints all of its contents.
- Read a file line by line and display only lines that contain the word
PHP. - Load a file into an array and count how many lines it contains.
Mini Project / Task
Build a simple log viewer that reads a server log file and displays only lines containing WARNING or ERROR.
Challenge (Optional)
Create a script that reads a CSV file line by line and prints each row as a formatted sentence without loading the entire file into memory.
Detailed Introduction
Writing files in PHP means saving data from your program into a file on the server. This is useful when you want to store logs, export reports, cache content, save user-generated text, or generate configuration and CSV files. In real applications, file writing is common in contact form logging, invoice generation, backup scripts, and application diagnostics. PHP provides several built-in functions for this task, from simple one-line writing to advanced handling with file pointers. Understanding file writing helps developers move beyond screen output and start persisting data in a practical way. Since PHP often runs on a web server, file writing also introduces important ideas such as permissions, safe paths, overwriting versus appending, and error handling.
Core Concepts & Sub-types
file_put_contents()
This is the simplest way to write data to a file. It can create a file if it does not exist, overwrite existing content by default, or append content with a flag.
fopen() with fwrite()
This method gives more control. You open a file in a specific mode, write data, then close it. It is useful for larger workflows and repeated writes.
Write Modes
w creates or truncates a file before writing. a appends data to the end. x creates a new file and fails if it already exists. These modes affect safety and behavior.
Step-by-Step Explanation
To write with file_put_contents(), provide a file path and the data string: file_put_contents('notes.txt', 'Hello');. To append, add FILE_APPEND. For more control, use fopen() with a mode like 'w' or 'a', then pass the handle to fwrite(), and finally call fclose(). Always check if operations succeed because invalid paths or missing permissions can cause failure. In beginner projects, start with simple relative paths, but in professional code, build full safe paths carefully.
Comprehensive Code Examples
Basic example
<?php
$result = file_put_contents('message.txt', 'Welcome to PHP file writing');
if ($result !== false) {
echo 'File written successfully';
} else {
echo 'Failed to write file';
}Real-world example
<?php
$logMessage = 'User visited page at ' . date('Y-m-d H:i:s') . PHP_EOL;
$result = file_put_contents('access.log', $logMessage, FILE_APPEND);
if ($result === false) {
echo 'Could not write to log';
}Advanced usage
<?php
$file = fopen('report.csv', 'w');
if ($file) {
fwrite($file, "Name,Score" . PHP_EOL);
fwrite($file, "Alice,95" . PHP_EOL);
fwrite($file, "Bob,88" . PHP_EOL);
fclose($file);
echo 'CSV created';
} else {
echo 'Unable to open file';
}Common Mistakes
- Overwriting by accident: Using
file_put_contents()withoutFILE_APPENDreplaces old content. Use append mode when needed. - Forgetting to close files: With
fopen(), always callfclose()after writing. - Ignoring permissions: A script may fail if the server cannot write to the folder. Check folder permissions and file paths.
- Using wrong paths: Relative paths can point somewhere unexpected. Verify the working directory carefully.
Best Practices
- Check return values to confirm the write was successful.
- Use
FILE_APPENDfor logs and historical records. - Prefer clear, predictable file paths inside controlled directories.
- Write structured formats like CSV or JSON when data may be reused later.
- Handle errors gracefully instead of assuming the file operation will always work.
Practice Exercises
- Create a PHP script that writes the text
Hello Fileintohello.txt. - Create another script that appends the current date and time to
events.logevery time it runs. - Use
fopen()andfwrite()to create a file namednames.txtcontaining three names on separate lines.
Mini Project / Task
Build a simple visitor logger that stores each page visit in a text file with the timestamp and visitor IP address.
Challenge (Optional)
Create a PHP script that accepts an array of products and writes them into a CSV file with headers such as product name, price, and quantity.
Detailed Introduction
File upload in PHP allows users to send files from their browser to your server through an HTML form. This is commonly used for profile pictures, PDFs, resumes, invoices, spreadsheets, and product images in web applications. PHP supports uploads through the global $_FILES array, which stores metadata such as file name, temporary path, size, and upload errors. In real life, file uploads appear in social platforms, job portals, e-commerce dashboards, school systems, and admin panels. Although uploading seems simple, it exists as a controlled process because servers must protect against invalid files, large uploads, overwritten filenames, and malicious content. A good upload workflow validates the request method, checks for errors, restricts size, verifies MIME type and extension, generates a safe unique filename, and moves the file from PHP's temporary directory into a permanent folder. Understanding this topic is essential because file handling combines forms, validation, security, and filesystem operations in one practical feature.
Core Concepts & Sub-types
HTML Form Requirements
The form must use method="POST" and enctype="multipart/form-data". Without the correct encoding type, the file will not be sent properly.
The $_FILES Array
PHP stores upload details in $_FILES with keys like name, tmp_name, size, type, and error.
Single vs Multiple Uploads
A form can upload one file or many files using an input name like photos[] and the multiple attribute.
Validation
Important checks include upload error code, allowed extension, MIME type, size limit, and destination directory existence.
Storage
Uploaded files first go to a temporary path, then must be saved permanently with move_uploaded_file().
Step-by-Step Explanation
First, create a form with a file input. Second, submit it using POST. Third, access the uploaded file through $_FILES['your_input_name']. Fourth, inspect the error value to confirm success. Fifth, validate size and type. Sixth, create a safe file name, usually with uniqid() or a random string. Finally, move the file to a writable folder such as uploads/. The basic syntax pattern is: read file info, validate, then call move_uploaded_file($tmp, $destination).
Comprehensive Code Examples
Basic example:
<form action="" method="POST" enctype="multipart/form-data"><input type="file" name="avatar"><button type="submit">Upload</button></form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$file = $_FILES['avatar'];
if ($file['error'] === 0) {
move_uploaded_file($file['tmp_name'], 'uploads/' . $file['name']);
echo 'Upload successful';
}
}
?>Real-world example with validation:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$file = $_FILES['avatar'];
$allowed = ['jpg', 'jpeg', 'png'];
$maxSize = 2 * 1024 * 1024;
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($file['error'] !== 0) {
echo 'Upload error.';
} elseif (!in_array($ext, $allowed)) {
echo 'Invalid file type.';
} elseif ($file['size'] > $maxSize) {
echo 'File too large.';
} else {
$newName = uniqid('img_', true) . '.' . $ext;
$destination = 'uploads/' . $newName;
if (move_uploaded_file($file['tmp_name'], $destination)) {
echo 'Saved successfully.';
}
}
}
?>Advanced multiple upload example:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
foreach ($_FILES['photos']['name'] as $i => $name) {
$tmp = $_FILES['photos']['tmp_name'][$i];
$error = $_FILES['photos']['error'][$i];
if ($error === 0) {
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$newName = uniqid('photo_', true) . '.' . $ext;
move_uploaded_file($tmp, 'uploads/' . $newName);
}
}
}
?>
<form method="POST" enctype="multipart/form-data"><input type="file" name="photos[]" multiple><button type="submit">Send</button></form>Common Mistakes
Forgetting
enctype="multipart/form-data". Fix: always add it to upload forms.Using the original filename directly. Fix: generate a unique safe filename to avoid overwriting and security issues.
Skipping validation. Fix: check error code, file size, extension, and MIME type before saving.
Best Practices
Store uploads outside the public web root when possible.
Allow only specific file types and set strict size limits.
Rename files with unique identifiers instead of trusting user-provided names.
Create the upload directory carefully and ensure correct permissions.
Save file metadata in a database if the project needs tracking or retrieval.
Practice Exercises
Build a form that uploads one image and saves it into an
uploadsfolder.Add validation so only PNG and JPG files under 1 MB are accepted.
Create a multiple-file upload form and loop through the uploaded files.
Mini Project / Task
Build a profile photo uploader that accepts one image, validates it, renames it uniquely, saves it in an upload directory, and displays a success or error message.
Challenge (Optional)
Extend the uploader so it stores the uploaded file path and original filename in a database table, then shows a list of previously uploaded files.
Detailed Introduction
PHP Date and Time features allow developers to create, format, compare, and manipulate dates and timestamps inside applications. They exist because almost every real system depends on time-based data, such as user registrations, blog post publishing, order history, booking systems, reminders, subscriptions, and reporting dashboards. In PHP, working with date and time can be as simple as displaying todayās date or as advanced as calculating intervals between events across time zones. Real-life use cases include showing the current server time, storing a customerās purchase date, calculating an event deadline, scheduling tasks, and converting times for international users. PHP provides procedural functions like date() and object-oriented tools like DateTime and DateInterval. Beginners often start with timestamps and formatting, then move into safer and more flexible DateTime-based workflows. Understanding this topic is important because incorrect date handling can cause bugs in billing systems, booking apps, and authentication logic. Mastering PHP Date and Time helps you build applications that are accurate, readable, and reliable.
Core Concepts & Sub-types
Timestamps
A timestamp is the number of seconds since January 1, 1970. PHP uses timestamps for quick time calculations.
Formatting Dates
The date() function formats a timestamp into a human-readable string like 2026-03-27.
DateTime Objects
DateTime offers a more modern and flexible way to create and modify dates than basic functions.
Time Zones
PHP can work with different regions using date_default_timezone_set() or DateTimeZone.
Date Calculations
You can add or subtract days, compare dates, and calculate differences using modify() and diff().
Step-by-Step Explanation
Start by setting a timezone so your application behaves predictably. Next, use date() to format the current date. Common format characters include Y for four-digit year, m for month, d for day, H for hour, i for minutes, and s for seconds. To create a specific date, use new DateTime('2026-12-25'). To change it, call modify('+7 days'). To compare two dates, create two DateTime objects and use diff() for an interval. For Unix timestamps, use time() to get the current timestamp. If you need to convert a readable date into a timestamp, use strtotime().
Comprehensive Code Examples
<?php
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s');
?>Basic example: display the current date and time.
<?php
$orderDate = new DateTime('now');
$deliveryDate = new DateTime('now');
$deliveryDate->modify('+5 days');
echo 'Ordered: ' . $orderDate->format('Y-m-d');
echo '<br>Estimated delivery: ' . $deliveryDate->format('Y-m-d');
?>Real-world example: estimate a delivery date.
<?php
$start = new DateTime('2026-03-01 10:00:00', new DateTimeZone('America/New_York'));
$end = new DateTime('2026-03-10 18:30:00', new DateTimeZone('America/New_York'));
$interval = $start->diff($end);
echo $interval->days . ' days difference';
echo '<br>Start: ' . $start->format('Y-m-d H:i:s T');
echo '<br>End: ' . $end->format('Y-m-d H:i:s T');
?>Advanced usage: compare two dates with timezone awareness.
Common Mistakes
- Forgetting to set a timezone, which can produce incorrect times. Fix: always define a timezone explicitly.
- Using the wrong format characters, such as
mfor minutes instead ofi. Fix: memorize common format symbols. - Relying only on
strtotime()for complex logic. Fix: useDateTimefor safer date manipulation.
Best Practices
- Prefer
DateTimeover older procedural functions for maintainable code. - Store dates in a standard format like
Y-m-d H:i:sor UTC in databases. - Convert to the userās timezone only when displaying data.
- Keep formatting separate from calculation logic.
Practice Exercises
- Display the current date in the format
d-m-Y. - Create a DateTime object for your birthday and print the day of the week.
- Calculate how many days remain until the end of the current year.
Mini Project / Task
Build a small PHP script that shows todayās date, current time, and a deadline exactly 7 days from now for a task submission system.
Challenge (Optional)
Create a script that accepts two dates and prints the difference in years, months, and days using DateTime::diff().
Detailed Introduction
In PHP, include and require are language constructs used to insert the contents of one PHP file into another. They exist to help developers avoid repeating code and to keep applications organized. Instead of writing the same header, footer, database connection, or configuration settings in many files, you can place that logic in a separate file and load it when needed. In real projects, this is extremely common. For example, a website may have one shared navigation file, one config file, and one reusable functions file. By including them where needed, updates become faster and safer because a single change affects every page that uses that file. The key difference is error handling: include raises a warning if the file is missing and the script may continue, while require raises a fatal error and stops execution. This matters when deciding whether a file is optional or essential.
Core Concepts & Sub-types
include
Use include when the file is helpful but not absolutely required for the page to run. If the file cannot be found, PHP shows a warning and continues executing the remaining code.
require
Use require when the file is essential, such as a database connection, constants, or core functions. If the file is missing, execution stops immediately.
include_once
This works like include but prevents the same file from being loaded more than once. It is useful when redeclaring functions or classes would cause errors.
require_once
This works like require and also ensures the file is loaded only one time. It is commonly used for configuration and class files.
Step-by-Step Explanation
The basic syntax is simple: write the construct, then provide the file path as a string. Example: include 'header.php'; or require 'config.php';. PHP reads the target file and inserts its contents at that location. Paths can be relative, such as 'includes/header.php', or built dynamically using directory constants like __DIR__ for safer file references. Beginners should know that if an included file contains PHP code, that code runs in the current script context, so variables may be shared depending on scope. For reliability, many developers prefer require_once __DIR__ . '/config.php'; because it avoids duplicate loading and reduces path issues.
Comprehensive Code Examples
Basic example
<?php
include 'header.php';
echo "<h1>Home Page</h1>";
include 'footer.php';
?>Real-world example
<?php
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';
$pageTitle = "Dashboard";
include __DIR__ . '/includes/header.php';
echo "Welcome, user!";
include __DIR__ . '/includes/footer.php';
?>Advanced usage
<?php
function loadView($viewName) {
$path = __DIR__ . '/views/' . $viewName . '.php';
if (file_exists($path)) {
include $path;
} else {
echo "View not found.";
}
}
require_once __DIR__ . '/config/app.php';
loadView('profile');
?>Common Mistakes
- Using
includefor critical files: If a required config file is missing, the page may continue in a broken state. Userequireinstead. - Including the same file multiple times: This can redeclare functions or classes. Use
include_onceorrequire_once. - Wrong file paths: Relative paths may fail depending on script location. Prefer
__DIR__to build absolute paths.
Best Practices
- Use
require_oncefor essential files like configuration, helper functions, and class definitions. - Store reusable files in organized folders such as
includes,config, andviews. - Use
__DIR__for predictable paths across environments. - Keep included files focused on one responsibility, such as header layout or database setup.
Practice Exercises
- Create a
header.phpandfooter.php, then include both in anindex.phppage. - Build a
config.phpfile with two variables and load it into another file usingrequire. - Create a file with a custom function, then test the difference between
includeandinclude_onceby loading it twice.
Mini Project / Task
Build a simple multi-file PHP page that uses separate files for configuration, header, navigation, content, and footer. Load critical files with require_once and layout files with include.
Challenge (Optional)
Create a small view loader function that accepts a page name, safely checks whether the file exists, and includes the correct template from a views folder.
Detailed Introduction
PHP error handling is the process of detecting, reporting, logging, and responding to problems that happen while a script runs. These problems may include syntax mistakes, missing files, invalid function arguments, failed database connections, or unexpected user input. Error handling exists so developers can find bugs faster, prevent application crashes, and show safer messages to users instead of exposing sensitive technical details. In real projects, error handling is used in login systems, payment processing, file uploads, APIs, and database-driven applications. For example, if a user uploads an unsupported file, good error handling lets the application reject it cleanly and log the issue for review. In modern PHP, error handling is not just about displaying warnings; it also includes exceptions, custom handlers, and logging strategies that make applications more reliable and easier to maintain.
Core Concepts & Sub-types
PHP Errors
Traditional PHP errors include notices, warnings, and fatal errors. Notices are minor issues, warnings signal bigger problems but may allow execution to continue, and fatal errors stop the script.
Exceptions
Exceptions are objects that represent errors in a structured way. They can be thrown with throw and handled using try, catch, and finally.
Error Reporting
error_reporting() controls which errors PHP reports. During development, developers usually enable all errors.
Custom Error Handling
With set_error_handler(), you can define how non-fatal errors are processed. This is useful for logging or converting errors into exceptions.
Logging
Instead of showing raw errors to users, production apps often store them in logs using error_log().
Step-by-Step Explanation
First, enable reporting in development using error_reporting(E_ALL) and ini_set('display_errors', 1). Second, use try to wrap risky code. Third, place expected failure handling inside catch. Fourth, use finally for cleanup tasks such as closing resources. If you need custom behavior for standard PHP errors, register a handler with set_error_handler(). For production, turn off displayed errors and log them instead. This keeps user-facing pages clean and secure.
Comprehensive Code Examples
Basic example:
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
throw new Exception('Something went wrong');
} catch (Exception $e) {
echo 'Caught: ' . $e->getMessage();
}
?>Real-world example:
function divide($a, $b) {
if ($b == 0) {
throw new Exception('Division by zero is not allowed');
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (Exception $e) {
error_log($e->getMessage());
echo 'An error occurred while processing your request.';
}
?>Advanced usage:
set_error_handler(function($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
});
try {
include 'missing-file.php';
} catch (ErrorException $e) {
error_log('Custom handled: ' . $e->getMessage());
echo 'A system error was safely handled.';
} finally {
echo ' Cleanup complete.';
}
?>Common Mistakes
- Displaying errors in production: This can leak file paths and server details. Fix it by disabling display and enabling logging.
- Using exceptions for everything without planning: Not every minor condition needs an exception. Use them for exceptional situations.
- Forgetting to catch specific exceptions: Catching only generic exceptions may hide important context. Use targeted exception classes when possible.
- Ignoring logs: Handling an error without recording it makes debugging harder. Always log meaningful failures.
Best Practices
- Enable all errors in development so bugs are found early.
- Hide errors from users in production and write them to logs.
- Use clear exception messages that help developers diagnose issues.
- Create custom exception classes for domain-specific problems.
- Keep user messages friendly while storing technical details internally.
Practice Exercises
- Create a script that throws an exception when a number is negative and catches it with a custom message.
- Write a function that checks whether a file exists before reading it, and handle the failure using error logging.
- Set a custom error handler that converts a warning into an
ErrorException.
Mini Project / Task
Build a small form-processing script that validates name and email input, throws exceptions for invalid data, logs the technical error, and shows a safe message to the user.
Challenge (Optional)
Create a custom exception class for database-related errors and use it in a mock connection function that handles both logging and user-friendly output.
Detailed Introduction
PHP Filters are built-in tools that help you validate and sanitize data before your application uses it. In real projects, users submit emails, URLs, numbers, and text through forms, query strings, and APIs. Filters exist to reduce bad input, improve security, and make your code more reliable. Validation checks whether data matches an expected format, while sanitization cleans data by removing unwanted or unsafe characters. For example, an email field can be validated, while a text comment can be sanitized before storage or output. Filters are commonly used in login forms, contact pages, search boxes, admin dashboards, and API endpoints where trusted and untrusted input must be handled carefully.
Core Concepts & Sub-types
Validation Filters
Validation filters confirm that a value is acceptable. Common examples include FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_URL, FILTER_VALIDATE_INT, and FILTER_VALIDATE_BOOLEAN.
Sanitization Filters
Sanitization filters clean input so it becomes safer or more standardized. Examples include FILTER_SANITIZE_EMAIL, FILTER_SANITIZE_URL, and FILTER_SANITIZE_NUMBER_INT.
Filter Functions
The main functions are filter_var() for a single value, filter_input() for external input like GET or POST, and filter_var_array() for validating multiple fields at once.
Step-by-Step Explanation
Use filter_var(value, filter, options). The first argument is the data, the second is the filter constant, and the third is optional configuration such as flags or ranges. If you want to validate an integer between 1 and 100, pass an options array with min_range and max_range. For request data, filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL) reads and validates directly from a submitted form. Always check the return value carefully because failed validation usually returns false, while sanitized data returns the cleaned value.
Comprehensive Code Examples
Basic example
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
} else {
echo "Invalid email";
}
?>Real-world example
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = filter_input(INPUT_POST, "name", FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if (!$email) {
echo "Please enter a valid email address.";
} else {
echo "Welcome, " . $name;
}
}
?>Advanced usage
$data = [
"email" => "[email protected]",
"age" => "27",
"website" => "https://example.com"
];
$rules = [
"email" => FILTER_VALIDATE_EMAIL,
"age" => [
"filter" => FILTER_VALIDATE_INT,
"options" => ["min_range" => 18, "max_range" => 60]
],
"website" => FILTER_VALIDATE_URL
];
$result = filter_var_array($data, $rules);
print_r($result);
?>Common Mistakes
Using sanitization when validation is required. Fix: validate important fields like email, age, and URL after or instead of sanitizing.
Assuming sanitized data is automatically safe for HTML output. Fix: still escape output appropriately when rendering content.
Not checking for
falseafter validation. Fix: always handle invalid input with clear error messages.
Best Practices
Validate all user input at the boundary of your application.
Use specific filters instead of generic string cleanup whenever possible.
Combine filters with server-side business rules such as length checks and required fields.
Keep validation logic organized in one place for easier maintenance.
Practice Exercises
Create a script that checks whether a submitted email address is valid.
Build a form that accepts age and validates that it is an integer between 1 and 120.
Sanitize a phone number input so only digits and number signs remain where appropriate.
Mini Project / Task
Build a small registration validator that accepts name, email, website, and age, then sanitizes text fields and validates the structured fields before displaying success or error messages.
Challenge (Optional)
Create a reusable PHP function that accepts a data array and a filter rule array, then returns validated results and a list of field-specific errors.
Detailed Introduction
JSON stands for JavaScript Object Notation. In PHP, JSON is used to exchange data between applications, browsers, APIs, mobile apps, and databases in a lightweight text format. It exists because systems often need a simple, language-independent way to send structured data such as users, products, orders, and settings. In real life, PHP uses JSON when returning API responses, reading configuration files, storing flexible metadata, and communicating with frontend frameworks like React or Vue. PHP provides built-in functions such as json_encode() and json_decode() so developers can convert arrays and objects into JSON text and turn JSON text back into usable PHP data structures.
Core Concepts & Sub-types
JSON Objects
A JSON object uses curly braces and stores key-value pairs, such as {"name":"Ali"}. In PHP, associative arrays often become JSON objects.
JSON Arrays
A JSON array uses square brackets and stores ordered values, such as [1,2,3]. In PHP, indexed arrays usually become JSON arrays.
Encoding
Encoding means converting PHP arrays or objects into JSON text using json_encode().
Decoding
Decoding means converting JSON text into a PHP object or associative array using json_decode().
Error Handling
Invalid JSON, wrong character encoding, or malformed data can cause problems. PHP offers json_last_error_msg() and flags like JSON_PRETTY_PRINT and JSON_UNESCAPED_UNICODE.
Step-by-Step Explanation
To create JSON in PHP, first prepare an array or object. Next, pass it to json_encode(). To read JSON, receive the JSON string, then call json_decode(). If you want an associative array instead of an object, pass true as the second argument. Example flow: create data, encode it, output or save it, then decode it later when needed. Always check whether decoding succeeded before using the result.
Comprehensive Code Examples
Basic example
$user = [
"name" => "Sara",
"age" => 25,
"is_admin" => false
];
$json = json_encode($user);
echo $json;
?>Real-world example
header('Content-Type: application/json');
$products = [
["id" => 1, "name" => "Laptop", "price" => 1200],
["id" => 2, "name" => "Mouse", "price" => 25]
];
echo json_encode(["status" => "success", "data" => $products]);
?>Advanced usage
$jsonText = '{"title":"PHP Course","tags":["php","json"],"published":true}';
$data = json_decode($jsonText, true);
if (json_last_error() === JSON_ERROR_NONE) {
echo $data["title"] . "
";
echo implode(", ", $data["tags"]);
} else {
echo "JSON Error: " . json_last_error_msg();
}
$pretty = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
echo "$pretty
";
?>Common Mistakes
- Forgetting the second argument in
json_decode(): withouttrue, PHP returns an object, not an associative array. Fix by usingjson_decode($json, true)when array access is needed. - Not checking JSON errors: invalid JSON may silently fail. Fix by checking
json_last_error()orjson_last_error_msg(). - Outputting extra text before JSON: spaces, HTML, or warnings can break API responses. Fix by sending clean output and correct headers.
Best Practices
- Use
header('Content-Type: application/json')when returning JSON from APIs. - Prefer associative arrays for easier beginner-friendly access when decoding.
- Validate incoming JSON before processing sensitive data.
- Use formatting flags like
JSON_PRETTY_PRINTduring development for readability. - Keep API response structures consistent, such as always returning
status,message, anddata.
Practice Exercises
- Create an associative array with your name, age, and favorite language, then convert it to JSON.
- Write a PHP script that decodes a JSON string containing three city names and prints each city.
- Build a JSON response for a product with
id,name, andprice, then display it in the browser.
Mini Project / Task
Build a small PHP script that stores a list of students in an array, converts it to JSON, and returns it as an API-style response with a status field.
Challenge (Optional)
Create a PHP script that accepts a JSON string representing a shopping cart, decodes it, calculates the total price, and returns the result as JSON.
Detailed Introduction
Object-Oriented Programming, or OOP, is a programming style that organizes code into reusable blueprints called classes and working units called objects. In PHP, OOP exists to make large applications easier to structure, maintain, and scale. Instead of writing everything as separate functions and variables, you group related data and behavior together. For example, in a shopping app, a Product class can store a product name, price, and methods like calculateDiscount(). This mirrors real life because objects in code often represent real entities such as users, orders, invoices, or blog posts. OOP is widely used in modern PHP frameworks like Laravel, Symfony, and WordPress plugin development because it improves readability, reuse, and collaboration in team projects.
Core Concepts & Sub-types
Class
A class is a blueprint that defines properties and methods.
Object
An object is an instance created from a class.
Properties
Properties are variables that belong to a class, such as $name or $price.
Methods
Methods are functions inside a class that define behavior.
$this
The $this keyword refers to the current object and is used to access its properties and methods.
Constructor
A constructor, written as __construct(), runs automatically when an object is created and is useful for setting starting values.
Step-by-Step Explanation
To create OOP code in PHP, first define a class with the class keyword. Inside it, add properties using visibility like public. Then create methods to work with those properties. To create an object, use the new keyword. If a constructor exists, pass required values when creating the object. Use object access syntax -> to read properties or call methods. For example, $car->startEngine() calls a method on the car object. Beginners should remember that each object gets its own data, even when created from the same class.
Comprehensive Code Examples
Basic example
<?php
class User {
public $name;
public function sayHello() {
return "Hello, " . $this->name;
}
}
$user = new User();
$user->name = "Aisha";
echo $user->sayHello();Real-world example
<?php
class Product {
public $name;
public $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getLabel() {
return $this->name . " costs $" . $this->price;
}
}
$product = new Product("Keyboard", 49.99);
echo $product->getLabel();Advanced usage
<?php
class BankAccount {
public $owner;
public $balance;
public function __construct($owner, $balance = 0) {
$this->owner = $owner;
$this->balance = $balance;
}
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}
public function withdraw($amount) {
if ($amount <= $this->balance) {
$this->balance -= $amount;
}
}
}
$account = new BankAccount("John", 100);
$account->deposit(50);
$account->withdraw(30);
echo $account->balance;Common Mistakes
- Forgetting
$this->when accessing class properties inside methods. Fix: use$this->propertyName. - Creating a class but forgetting to instantiate it with
new. Fix: create objects before using methods. - Confusing properties with local variables. Fix: remember that class properties belong to the object and need
$this->inside methods.
Best Practices
- Use class names that describe real entities, such as
UserorOrder. - Keep each class focused on one clear responsibility.
- Use constructors to initialize important values consistently.
- Write methods with clear names that describe actions.
Practice Exercises
- Create a
Carclass with properties for brand and model, then add a method that returns both values in one sentence. - Create a
Studentclass with a constructor that accepts name and age, then print the student details. - Create a
Bookclass with a method calledgetSummary()that returns the title and author.
Mini Project / Task
Build a simple Invoice class that stores an item name, quantity, and price, then adds a method to calculate the total amount.
Challenge (Optional)
Create a Rectangle class with width and height, then add methods to calculate area and perimeter for different rectangle objects.
Detailed Introduction
Classes and objects are the foundation of object-oriented programming in PHP. A class is a blueprint that defines data and behavior, while an object is an actual instance created from that blueprint. This approach exists to organize code into reusable, meaningful units. Instead of writing scattered variables and functions, you group related values and actions together. In real life, classes and objects are used in e-commerce systems for products and carts, in banking apps for accounts and transactions, and in content systems for users, posts, and comments. They make code easier to read, test, expand, and maintain as applications grow.
Core Concepts & Sub-types
Class
A class defines properties and methods. Properties store data; methods perform actions.
Object
An object is created from a class using the new keyword. Each object can hold its own property values.
Properties
Properties are variables inside a class, such as a product name or price.
Methods
Methods are functions inside a class, such as calculating a discount or displaying details.
Constructor
The __construct() method runs automatically when an object is created and is commonly used to set initial values.
Step-by-Step Explanation
To create a class, use the class keyword followed by a class name in PascalCase. Inside the class, define properties with visibility like public, then define methods. To create an object, write $item = new ClassName();. Access properties and methods with the object operator ->, such as $item->name or $item->getName(). Inside the class, use $this to refer to the current object. If a constructor is present, pass values during object creation so each object starts with meaningful data.
Comprehensive Code Examples
Basic example
class Car {
public $brand;
public function showBrand() {
return $this->brand;
}
}
$car = new Car();
$car->brand = "Toyota";
echo $car->showBrand();Real-world example
class Product {
public $name;
public $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getLabel() {
return $this->name . " costs $" . $this->price;
}
}
$product = new Product("Keyboard", 49.99);
echo $product->getLabel();Advanced usage
class BankAccount {
public $owner;
public $balance;
public function __construct($owner, $balance = 0) {
$this->owner = $owner;
$this->balance = $balance;
}
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}
public function withdraw($amount) {
if ($amount <= $this->balance) {
$this->balance -= $amount;
}
}
}
$account = new BankAccount("Ava", 500);
$account->deposit(200);
$account->withdraw(100);
echo $account->balance;Common Mistakes
Forgetting
newwhen creating an object. Fix: use$obj = new MyClass();.Using
$thisoutside a class method. Fix: use it only inside object methods.Accessing properties with
.instead of->. Fix: use$object->property.
Best Practices
Use clear class names like
User,Order, andInvoice.Initialize important values through constructors for safer object creation.
Keep each class focused on one responsibility to improve maintainability.
Practice Exercises
Create a
Bookclass withtitleandauthorproperties, then print both values using a method.Create a
Studentclass with a constructor that accepts name and grade, then display a summary string.Build a
Rectangleclass with width and height, and add a method that returns the area.
Mini Project / Task
Build a simple Task class for a to-do app with properties for title and completed status, plus methods to mark a task as done and display its current state.
Challenge (Optional)
Create a ShoppingCartItem class with name, price, and quantity, then add a method that returns the total cost for that item.
Detailed Introduction
In PHP object-oriented programming, properties are variables that belong to a class, and methods are functions that belong to a class. Together, they define what an object has and what an object does. For example, a User object may have properties like name and email, and methods like login() or logout(). This structure exists to model real-world entities in a clean, reusable way. In real applications, properties store state such as product price, order status, or account balance, while methods perform actions such as calculating totals, validating input, or updating records. Learning properties and methods is a major step toward writing maintainable PHP applications.
Core Concepts & Sub-types
Properties
Properties store data inside an object. They are declared inside a class and accessed through an object using ->. A property can be public, protected, or private, though beginners usually start with public.
Methods
Methods define behavior. They are written like functions inside a class. Methods can read or change properties using $this, which refers to the current object.
Instance Context
Each object gets its own property values. Two objects from the same class can share the same methods but hold different data.
Step-by-Step Explanation
First, create a class with the class keyword. Next, add properties inside the class body. Then define methods with the function keyword. To create an object, use new. To access a property, write $object->propertyName. To call a method, write $object->methodName(). Inside a method, use $this->propertyName to access that object's data. This is important because methods usually work with the current object's state.
Comprehensive Code Examples
Basic example
class Car {
public $brand = "Toyota";
public $color = "Blue";
public function start() {
return "The car has started.";
}
}
$car = new Car();
echo $car->brand;
echo $car->start();Real-world example
class Product {
public $name;
public $price;
public function showLabel() {
return $this->name . " costs $" . $this->price;
}
}
$product = new Product();
$product->name = "Keyboard";
$product->price = 49.99;
echo $product->showLabel();Advanced usage
class BankAccount {
public $owner;
public $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
public function withdraw($amount) {
if ($amount <= $this->balance) {
$this->balance -= $amount;
return "Withdrawal successful";
}
return "Insufficient funds";
}
}
$account = new BankAccount();
$account->owner = "Sara";
$account->deposit(500);
echo $account->withdraw(200);
echo $account->balance;Common Mistakes
- Forgetting
$this->inside methods: writingbalanceinstead of$this->balance. Fix: always use$this->for current object properties. - Using
.instead of->: beginners confuse string concatenation with object access. Fix: use->for properties and methods on objects. - Calling a method without parentheses: writing
$user->logininstead of$user->login(). Fix: methods need parentheses, even when empty.
Best Practices
- Use clear property names such as
title,price, andstatus. - Keep methods focused on one responsibility.
- Use methods to control how object data changes instead of changing everything directly.
- Initialize sensible default values when possible.
- Prefer real-world class design so code is easier to understand and extend.
Practice Exercises
- Create a
Bookclass with propertiestitleandauthor, plus a method that displays both values. - Create a
Studentclass with a propertynameand a methodintroduce()that returns a greeting. - Create a
LightBulbclass with a propertyisOnand methodsturnOn()andturnOff().
Mini Project / Task
Build a ShoppingCartItem class with properties for product name, quantity, and price, and a method that returns the total cost for that item.
Challenge (Optional)
Create a Task class with properties for task name and completion status, then add methods to mark the task as complete and display its current state.
Detailed Introduction
Constructors and destructors are special methods in PHP classes that control what happens when an object is created and when it is destroyed. A constructor is usually used to prepare an object with the data it needs from the start. A destructor is used for cleanup work before the object is removed from memory. In real projects, constructors help initialize database settings, user data, configuration values, or dependencies. Destructors can help close files, release resources, or log final actions. These methods exist because objects often need a predictable lifecycle. Instead of creating an object and then manually setting every property one by one, a constructor lets you enforce required values immediately. This makes code safer and easier to maintain. Destructors are less commonly used than constructors, but they are still important when your class manages temporary resources or needs final cleanup behavior.
Core Concepts & Sub-types
Constructor: __construct()
The constructor runs automatically when an object is instantiated with new. It is commonly used to assign initial property values and validate required inputs.
Destructor: __destruct()
The destructor runs automatically when an object is no longer needed or when the script ends. It is commonly used for cleanup tasks such as logging, closing handles, or freeing resources.
Parameterized Constructors
A constructor can accept arguments so every new object starts with meaningful data.
Default Values in Constructors
You can make constructor parameters optional by assigning default values. This gives flexibility while keeping initialization centralized.
Step-by-Step Explanation
To define a constructor, create a class and add a method named __construct(). Inside it, receive parameters and assign them to object properties using $this->property. To define a destructor, add a method named __destruct(). PHP automatically calls it later, so you never invoke it directly in normal use. The general flow is simple: define class properties, create a constructor to initialize them, optionally define a destructor for cleanup, then create objects with new ClassName(...).
Comprehensive Code Examples
Basic Example
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$user = new User("Aisha");
echo $user->name;Real-world Example
<?php
class Logger {
private $fileName;
public function __construct($fileName = "app.log") {
$this->fileName = $fileName;
echo "Logger started for: " . $this->fileName;
}
public function log($message) {
echo "Writing: " . $message;
}
public function __destruct() {
echo "Logger closed.";
}
}
$logger = new Logger();
$logger->log("User signed in");Advanced Usage
<?php
class DatabaseConnection {
private $host;
private $database;
public function __construct($host, $database) {
$this->host = $host;
$this->database = $database;
echo "Connecting to {$this->host}/{$this->database}";
}
public function query($sql) {
echo "Running query: " . $sql;
}
public function __destruct() {
echo "Disconnecting from database";
}
}
$db = new DatabaseConnection("localhost", "shop");
$db->query("SELECT * FROM products");Common Mistakes
- Using the wrong method name such as
construct()instead of__construct(). Fix: always use the exact magic method name with two underscores. - Forgetting
$this->when assigning object properties. Fix: use$this->name = $name;inside class methods. - Expecting the destructor to run at a specific moment in every case. Fix: remember it usually runs when the object is destroyed or at script shutdown.
Best Practices
- Keep constructors focused on initialization only.
- Use constructor parameters to enforce required data early.
- Give optional parameters sensible default values.
- Use destructors only for cleanup, not major business logic.
- Avoid printing from destructors in production unless debugging or logging is intended.
Practice Exercises
- Create a
Bookclass with a constructor that accepts title and author, then display both properties. - Create a
Carclass with a constructor that uses a default value for color if none is provided. - Create a
SessionTrackerclass with a constructor that starts tracking and a destructor that displays a message when tracking ends.
Mini Project / Task
Build a simple ShoppingCart class where the constructor accepts a customer name and the destructor prints a closing message such as saving the cart session.
Challenge (Optional)
Create a FileManager class that accepts a file name in the constructor, simulates file usage through a method, and performs cleanup in the destructor with a final status message.
Detailed Introduction
Inheritance in PHP is an object-oriented programming feature that allows one class to reuse and extend the properties and methods of another class. The class being inherited from is called the parent class, base class, or superclass, while the class that receives and extends that behavior is called the child class or subclass. This exists to reduce code duplication, improve organization, and model real-world relationships such as Vehicle and Car, User and AdminUser, or Employee and Manager. In real applications, inheritance is used in frameworks, authentication systems, payment modules, and reusable domain models where several classes share common behavior but also need their own custom logic.
In PHP, inheritance is created using the extends keyword. A child class automatically gets access to public and protected members of the parent class, and it can also override methods to provide specialized behavior. This makes code easier to maintain because shared logic stays in one place. However, inheritance should be used only when there is a true āis-aā relationship. For example, a Dog is an Animal, so inheritance fits well. Understanding inheritance is essential before working with advanced topics like polymorphism, abstract classes, interfaces, and framework controllers or models.
Core Concepts & Sub-types
Single Inheritance
PHP supports single inheritance, meaning one child class can extend only one parent class directly.
Method Overriding
A child class can redefine a parent method to change or specialize behavior while keeping the same method name.
Access Inheritance
Public members are accessible everywhere, protected members are accessible inside the parent and child classes, and private members are not directly accessible in the child class.
Using parent
The parent:: keyword lets a child class call a parent constructor or overridden method.
Step-by-Step Explanation
First, define a parent class with shared properties and methods. Next, create a child class using class ChildClass extends ParentClass. The child class can immediately use inherited public and protected members. If needed, add new properties and methods specific to the child. To change inherited behavior, write a method in the child with the same name as the parent method. If the parent constructor must still run, call it with parent::__construct() inside the child constructor. This structure allows beginners to build class hierarchies clearly and safely.
Comprehensive Code Examples
Basic example
<?php
class Animal {
public function eat() {
echo "Eating...";
}
}
class Dog extends Animal {
public function bark() {
echo "Barking...";
}
}
$dog = new Dog();
$dog->eat();
$dog->bark();
?>Real-world example
<?php
class User {
protected string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function getRole(): string {
return "User";
}
}
class AdminUser extends User {
public function getRole(): string {
return "Admin";
}
}
$admin = new AdminUser("Sara");
echo $admin->getRole();
?>Advanced usage
<?php
class Employee {
protected string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function introduce(): string {
return "Employee: " . $this->name;
}
}
class Manager extends Employee {
private string $department;
public function __construct(string $name, string $department) {
parent::__construct($name);
$this->department = $department;
}
public function introduce(): string {
return parent::introduce() . " | Department: " . $this->department;
}
}
$manager = new Manager("Ali", "IT");
echo $manager->introduce();
?>Common Mistakes
Trying to access a parent class private property directly in the child. Fix: use
protectedor getter methods.Overriding a method with incompatible logic or visibility. Fix: keep method purpose consistent and do not reduce visibility.
Forgetting to call
parent::__construct()when parent setup is required. Fix: call it inside the child constructor.
Best Practices
Use inheritance only for a true is-a relationship.
Keep shared logic in the parent and specialized logic in the child.
Prefer protected members over public when child classes need controlled access.
Avoid deep inheritance chains because they make debugging harder.
Practice Exercises
Create a
Vehicleclass with amove()method, then create aCarclass that inherits from it and adds ahonk()method.Build a
Personclass and aStudentclass that extends it, then override a method to return a student-specific message.Create a parent class with a constructor and a child class that calls the parent constructor using
parent::__construct().
Mini Project / Task
Build a simple employee system with a parent Employee class and child classes like Developer and Designer, where each child overrides a method to describe its role.
Challenge (Optional)
Create a Shape parent class with a generic area method, then extend it into Rectangle and Circle classes that override the method and return their own area calculations.
Detailed Introduction
Encapsulation is one of the core principles of object-oriented programming in PHP. It means wrapping data and the methods that work with that data inside a class, while controlling how the outside world can access them. Instead of allowing any part of your program to directly change important values, encapsulation lets you define safe rules through methods such as getters, setters, and behavior-focused functions. This exists to protect object state, reduce bugs, and make code easier to maintain. In real-life applications, encapsulation is used everywhere: a bank account should not allow arbitrary balance changes, a user object should validate email updates, and an inventory item should prevent negative stock. In PHP, encapsulation is implemented mainly with visibility keywords like public, protected, and private. When used properly, it creates cleaner APIs for your classes and prevents accidental misuse by other developers. This is especially important in large projects where many files and team members interact with the same objects.
Core Concepts & Sub-types
Public Members
public properties and methods can be accessed from anywhere. Use them for behaviors that should be available to other parts of the program.
Private Members
private properties and methods can only be accessed inside the same class. They are best for internal state and helper logic that should stay hidden.
Protected Members
protected members are available inside the class and its child classes. They are useful when designing inheritance-based structures.
Getters and Setters
These are methods used to read or update private data safely. They can validate values before changing object state.
Behavior over Direct Access
Professional code often prefers methods like deposit() or changePassword() instead of exposing raw properties directly.
Step-by-Step Explanation
First, create a class. Next, define properties that hold data. Mark sensitive properties as private. Then create public methods to interact with that data. If needed, add validation before saving new values. This way, the object controls its own state. Syntax example: define a class, add private $name;, initialize it in __construct(), then expose methods like getName() and setName($name). The outside code uses methods, not direct property access. That is the heart of encapsulation.
Comprehensive Code Examples
Basic Example
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setName($name) {
if ($name !== '') {
$this->name = $name;
}
}
}
$user = new User('Ava');
echo $user->getName();
$user->setName('Liam');Real-world Example
class BankAccount {
private $balance = 0;
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}
public function withdraw($amount) {
if ($amount > 0 && $amount <= $this->balance) {
$this->balance -= $amount;
}
}
public function getBalance() {
return $this->balance;
}
}Advanced Usage
class Product {
private $price;
protected $name;
public function __construct($name, $price) {
$this->name = $name;
$this->setPrice($price);
}
public function setPrice($price) {
if (!is_numeric($price) || $price < 0) {
throw new InvalidArgumentException('Invalid price');
}
$this->price = $price;
}
public function getPrice() {
return $this->price;
}
}
class DigitalProduct extends Product {
public function getLabel() {
return $this->name . ' - $' . $this->getPrice();
}
}Common Mistakes
- Making everything public: This exposes internal data and allows unsafe changes. Use
privateby default unless external access is truly needed. - Setters without validation: Beginners often accept any value. Always check type, range, or format before updating properties.
- Accessing private properties directly: Code like
$obj->balancewill fail if the property is private. Use public methods instead.
Best Practices
- Keep properties private unless there is a strong reason not to.
- Expose meaningful behaviors such as
deposit()instead of generic unrestricted setters. - Validate data at the point of entry into the object.
- Use protected carefully for inheritance, not as a replacement for private.
- Design classes so they protect their own rules and remain internally consistent.
Practice Exercises
- Create a
Studentclass with a privategradeproperty and methods to set and get the grade only if it is between 0 and 100. - Build a
Temperatureclass with a private value and a method that prevents setting temperatures below absolute zero. - Create a
Walletclass with private balance and public methods to add and spend money safely.
Mini Project / Task
Build a LibraryBook class with private properties for title and availability status. Add public methods to borrow the book, return the book, and check whether it is available.
Challenge (Optional)
Create an Employee class where salary is private, can only be increased through a method, and cannot be reduced below zero. Add validation and a method to display a formatted summary.
Detailed Introduction
Polymorphism is an object-oriented programming concept that allows different classes to be treated through a shared interface, parent class, or contract while each class provides its own behavior. The word means āmany forms,ā and in PHP it helps you write flexible code that works with multiple object types without rewriting the same logic. For example, a payment system may process a CreditCardPayment, PayPalPayment, or BankTransferPayment using one common method. In real applications, polymorphism is used in payment gateways, notification systems, file storage drivers, logging tools, and API integrations. Instead of checking object types with many if statements, you let each object respond in its own way to the same method call. This makes code easier to extend, test, and maintain.
Core Concepts & Sub-types
Method Overriding
A child class redefines a method inherited from a parent class to provide specific behavior.
Interface-based Polymorphism
Multiple classes implement the same interface, so they can be used interchangeably through a shared contract.
Abstract Class Polymorphism
An abstract class defines common structure and partially shared behavior, while child classes complete the specific implementation.
Step-by-Step Explanation
First, create a parent class, interface, or abstract class with a common method such as send() or makeSound(). Next, create multiple classes that implement or override that method. Then write a function that accepts the shared type instead of a specific class. When you pass different objects into that function, PHP calls the correct version of the method based on the actual object. This is dynamic behavior at runtime. In beginner terms, one method name can trigger different results depending on which object is using it.
Comprehensive Code Examples
Basic example
class Animal {
public function speak(): string {
return "Some sound";
}
}
class Dog extends Animal {
public function speak(): string {
return "Bark";
}
}
class Cat extends Animal {
public function speak(): string {
return "Meow";
}
}
function makeAnimalSpeak(Animal $animal): void {
echo $animal->speak() . "
";
}
makeAnimalSpeak(new Dog());
makeAnimalSpeak(new Cat());Real-world example
interface PaymentMethod {
public function pay(float $amount): string;
}
class CreditCardPayment implements PaymentMethod {
public function pay(float $amount): string {
return "Paid $$amount using Credit Card";
}
}
class PayPalPayment implements PaymentMethod {
public function pay(float $amount): string {
return "Paid $$amount using PayPal";
}
}
function checkout(PaymentMethod $method, float $amount): void {
echo $method->pay($amount);
}
checkout(new CreditCardPayment(), 99.99);Advanced usage
abstract class Notifier {
abstract public function send(string $message): void;
public function log(string $message): void {
echo "Log: $message
";
}
}
class EmailNotifier extends Notifier {
public function send(string $message): void {
$this->log("Sending email");
echo "Email: $message
";
}
}
class SmsNotifier extends Notifier {
public function send(string $message): void {
$this->log("Sending SMS");
echo "SMS: $message
";
}
}
function notifyUser(Notifier $notifier, string $message): void {
$notifier->send($message);
}Common Mistakes
- Using many type checks: Beginners often use
iforswitchon class names. Fix it by calling a shared method on a parent type or interface. - Changing method signatures incorrectly: Child methods must remain compatible with parent or interface definitions.
- Forgetting interfaces or abstract classes: Without a shared contract, objects cannot be safely used polymorphically.
Best Practices
- Program to interfaces: Depend on contracts, not concrete classes.
- Keep methods focused: Shared polymorphic methods should do one clear job.
- Use meaningful names: Names like
pay(),send(), andrender()make behavior obvious. - Avoid deep inheritance: Prefer interfaces and composition when possible.
Practice Exercises
- Create an
Animalinterface with amove()method, then implement it inBirdandFish. - Build a
Shapeabstract class with anarea()method and createRectangleandCircleclasses. - Create a
Loggerinterface and implementFileLoggerandDatabaseLogger.
Mini Project / Task
Build a simple notification system where users can receive a message by email, SMS, or push notification using one shared method.
Challenge (Optional)
Create a report exporter system with PdfExporter, CsvExporter, and JsonExporter classes, and write one function that exports data using any exporter object.
Detailed Introduction
PHP MySQL Introduction explains how PHP connects to a MySQL database so web applications can work with persistent data. PHP handles the server-side logic, while MySQL stores structured information such as users, products, blog posts, and orders. Together, they power login systems, dashboards, e-commerce stores, content management systems, and internal business tools. In real life, whenever a website saves a registration form, loads account details, or lists products from a catalog, PHP usually sends SQL commands to MySQL and processes the returned results. This topic exists because dynamic applications need more than hardcoded values. A database lets you manage growing data reliably, search it quickly, and update it without changing application code.
Core Concepts & Sub-types
PHP
PHP is the server-side language that receives requests, runs logic, connects to the database, and generates output such as HTML or JSON.
MySQL
MySQL is a relational database management system that stores data in tables made of rows and columns.
SQL Queries
SQL commands include SELECT to read data, INSERT to add data, UPDATE to change data, and DELETE to remove data.
Connection Methods
PHP commonly uses MySQLi or PDO. MySQLi is MySQL-focused and beginner-friendly. PDO supports multiple databases and prepared statements with a consistent interface.
Step-by-Step Explanation
First, create a database in MySQL. Second, create a table such as users with fields like id, name, and email. Third, define connection details: host, username, password, and database name. Fourth, use PHP to connect with MySQLi or PDO. Fifth, write an SQL query. Sixth, execute the query and check for errors. Finally, fetch the results and display them in PHP. For beginners, think of the flow as: connect, query, fetch, display. Always validate user input before sending data to the database.
Comprehensive Code Examples
Basic example
$conn = new mysqli("localhost", "root", "", "school");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT id, name, email FROM users");
while ($row = $result->fetch_assoc()) {
echo $row["name"] . " - " . $row["email"] . "
";
}
$conn->close();
?>Real-world example
$conn = new mysqli("localhost", "root", "", "shop");
$stmt = $conn->prepare("INSERT INTO products (name, price) VALUES (?, ?)");
$name = "Keyboard";
$price = 49.99;
$stmt->bind_param("sd", $name, $price);
$stmt->execute();
echo "Product saved successfully";
$stmt->close();
$conn->close();
?>Advanced usage
$pdo = new PDO("mysql:host=localhost;dbname=company", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT name, department FROM employees WHERE department = ?");
$stmt->execute(["IT"]);
$employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($employees as $employee) {
echo $employee["name"] . " works in " . $employee["department"] . "
";
}
?>Common Mistakes
- Using wrong connection details: Double-check host, username, password, and database name.
- Writing raw queries with user input: Use prepared statements to prevent SQL injection.
- Ignoring error handling: Check connection and query results so failures are visible and easier to debug.
Best Practices
- Use prepared statements for all dynamic input.
- Store database credentials in a separate configuration file.
- Close statements and connections when finished.
- Keep SQL readable and use meaningful table and column names.
- Prefer PDO when you may support multiple database systems later.
Practice Exercises
- Create a PHP script that connects to a MySQL database and prints
Connected successfully. - Write a query that selects all rows from a
studentstable and displays each student name. - Build a form that inserts a new book title into a
bookstable using a prepared statement.
Mini Project / Task
Build a simple employee directory page that connects to MySQL, reads employee names and departments from a table, and displays them in the browser.
Challenge (Optional)
Create a small searchable product list where the user enters a category and PHP returns matching products from MySQL using a prepared statement.
Detailed Introduction
Connecting to a database in PHP means creating a communication link between your PHP application and a database server such as MySQL. This connection allows your application to store, read, update, and delete data. Without database connectivity, most dynamic applications would not function properly. Login systems, e-commerce stores, dashboards, blogs, and booking platforms all depend on database connections. In real life, when a user signs in, submits a form, or views saved content, PHP usually connects to a database behind the scenes. PHP commonly uses MySQL through extensions like MySQLi and PDO. PDO is especially popular because it supports multiple database systems and prepared statements, making code safer and more flexible. Understanding database connections is a core backend skill because nearly every serious PHP project requires reliable access to stored data.
Core Concepts & Sub-types
MySQLi
MySQLi is designed specifically for MySQL databases. It supports procedural and object-oriented styles and is a good choice when working only with MySQL.
PDO
PDO stands for PHP Data Objects. It offers a consistent interface for different database systems and is widely recommended for modern applications.
Connection Parameters
Most connections require a host, database name, username, password, and sometimes a port or charset.
Error Handling
A connection may fail because of wrong credentials, a missing database, or a stopped server. Good error handling helps you detect and respond safely.
Step-by-Step Explanation
To connect, first prepare your database credentials. Next, choose MySQLi or PDO. Then create the connection object using the required parameters. After that, check whether the connection succeeded. If it works, you can run queries. With PDO, the syntax usually starts by creating a new PDO object using a DSN string such as mysql:host=localhost;dbname=testdb;charset=utf8mb4. With MySQLi, you pass the host, username, password, and database name directly into the constructor. Beginners should remember that a successful connection does not display data by itself; it only opens the door for future queries.
Comprehensive Code Examples
Basic Example
<?php
$host = "localhost";
$dbname = "school";
$username = "root";
$password = "";
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully.";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>Real-world Example
<?php
$mysqli = new mysqli("localhost", "root", "", "company");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
echo "Database ready for employee operations.";
?>Advanced Usage
<?php
function connectDatabase() {
$host = "localhost";
$db = "shop";
$user = "root";
$pass = "";
try {
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
return $pdo;
} catch (PDOException $e) {
die("Database connection error.");
}
}
$pdo = connectDatabase();
echo "Reusable connection established.";
?>Common Mistakes
- Wrong credentials: Double-check host, username, password, and database name.
- Forgetting charset: Use
charset=utf8mb4to avoid encoding issues. - Displaying raw database errors in production: Show friendly messages to users and log technical details securely.
Best Practices
- Prefer PDO for flexibility and cleaner prepared statement support.
- Store credentials in a separate config file, not inside every script.
- Enable exception-based error handling for easier debugging.
- Use reusable connection functions or classes to avoid duplication.
- Never hardcode sensitive production credentials in public repositories.
Practice Exercises
- Create a PDO connection to a database named
libraryand display a success message. - Write a MySQLi connection script and handle connection failure with a custom message.
- Move your database credentials into variables and reuse them in a connection function.
Mini Project / Task
Build a PHP database configuration file that connects to a MySQL database and can be included in multiple pages of a small student management system.
Challenge (Optional)
Create a reusable PDO connection helper that supports switching between two database names by passing the database name as a function argument.
Detailed Introduction
CRUD stands for Create, Read, Update, Delete. These four actions represent the most common operations performed on data in web applications. In PHP, CRUD is usually connected to a database such as MySQL, where users can add records, view records, edit them, and remove them. Real-world examples include managing blog posts, customer lists, products, student records, and support tickets. CRUD exists because most software needs a reliable way to store and manipulate structured information. In a PHP application, CRUD commonly involves HTML forms, PHP scripts, SQL queries, and database connections using tools like PDO or MySQLi. Learning CRUD is essential because it turns PHP from a simple scripting language into a tool for building dynamic, data-driven systems.
Core Concepts & Sub-types
Create
Create means inserting new data into the database, usually through a form submitted with POST.
Read
Read means fetching data from the database and displaying it in tables, cards, profiles, or reports.
Update
Update means modifying existing records, often by loading current values into a form and saving changes.
Delete
Delete means removing records permanently or marking them as deleted in safer systems.
Supporting Concepts
CRUD also depends on database connections, SQL statements, prepared statements, form validation, and secure handling of user input.
Step-by-Step Explanation
First, connect PHP to the database using PDO. Second, create a table such as users with fields like id, name, and email. Third, build an HTML form for collecting input. Fourth, in PHP, read submitted form values from $_POST. Fifth, validate and sanitize the input. Sixth, run the correct SQL query: INSERT for create, SELECT for read, UPDATE for update, and DELETE for delete. Finally, show feedback to the user and refresh the displayed data. Beginners should focus on understanding how the form, PHP logic, and SQL query work together as one complete workflow.
Comprehensive Code Examples
Basic create example:
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
$name = $_POST['name'];
$email = $_POST['email'];
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute([$name, $email]);Read example:
$stmt = $pdo->query("SELECT * FROM users ORDER BY id DESC");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($users as $user) {
echo $user['name'] . " - " . $user['email'] . "
";
}Real-world update example:
$id = $_POST['id'];
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$stmt = $pdo->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?");
$stmt->execute([$name, $email, $id]);Advanced delete with validation:
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
if ($id) {
$stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
$stmt->execute([$id]);
}Common Mistakes
- Using raw SQL with user input: This risks SQL injection. Use prepared statements.
- Skipping validation: Empty or invalid emails may enter the database. Validate before saving.
- Forgetting the WHERE clause in UPDATE or DELETE: This can affect all rows. Always confirm the target record.
Best Practices
- Use PDO with prepared statements for security and flexibility.
- Validate and sanitize all input from forms.
- Show success and error messages for better user experience.
- Separate database logic from presentation when projects grow.
- Use confirmation before deleting important records.
Practice Exercises
- Create a PHP form that inserts a new book title and author into a database table.
- Display all books from the table in descending order by ID.
- Build an edit form that updates a selected book record.
Mini Project / Task
Build a simple student management page where users can add, list, edit, and delete student names and emails using PHP and MySQL.
Challenge (Optional)
Extend the CRUD app by adding a search box that filters records by name without reloading the whole application structure.
Detailed Introduction
Prepared statements are a secure and efficient way to run SQL queries in PHP when working with databases such as MySQL. Instead of building SQL strings by directly inserting user input, you write the SQL template first and send the data separately. This matters because direct string concatenation can lead to SQL injection, one of the most dangerous web security issues. Prepared statements are widely used in login systems, search features, registration forms, order processing, admin dashboards, and any feature that stores or retrieves data based on user input. In real projects, developers use prepared statements through PDO or MySQLi to make applications safer, easier to maintain, and often faster when the same query is executed multiple times.
Core Concepts & Sub-types
Prepared Query Template
This is the SQL statement with placeholders instead of raw values, such as SELECT * FROM users WHERE email = ? or named placeholders like :email.
Positional Placeholders
These use question marks. Values are bound in the exact order they appear.
Named Placeholders
These use labels like :name and :price. They improve readability, especially in longer queries.
Binding and Execution
After preparing the query, you bind values or pass them during execution. The database treats them as data, not SQL code.
PDO vs MySQLi
PDO supports multiple database systems and named placeholders. MySQLi is specific to MySQL. Both support prepared statements well.
Step-by-Step Explanation
First, create a database connection. Second, write SQL with placeholders. Third, prepare the statement. Fourth, bind or pass values. Fifth, execute the query. Sixth, fetch results for SELECT queries or check affected rows for INSERT, UPDATE, and DELETE operations. In PDO, a common flow is $stmt = $pdo->prepare($sql); then $stmt->execute([$value]);. For named placeholders, use an associative array. The placeholder names must match the keys exactly.
Comprehensive Code Examples
Basic Example
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
$sql = "SELECT * FROM users WHERE email = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(["[email protected]"]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);Real-world Example
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':name' => $name,
':email' => $email
]);Advanced Usage
$sql = "UPDATE products SET price = :price WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':price', 49.99);
$stmt->bindValue(':id', 7, PDO::PARAM_INT);
$stmt->execute();
$search = "%phone%";
$stmt = $pdo->prepare("SELECT * FROM products WHERE name LIKE :search");
$stmt->execute([':search' => $search]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);Common Mistakes
- Concatenating user input into SQL: Use placeholders instead of building raw SQL strings.
- Forgetting to call execute(): Preparing a statement alone does not run it.
- Mismatched placeholder names: Ensure
:emailin SQL matches the execution array key exactly. - Wrong LIKE usage: Put wildcards in the value, not around the placeholder inside quotes.
Best Practices
- Always use prepared statements for external input, even for numeric values.
- Prefer PDO for portability and clean syntax.
- Use named placeholders for readability in complex queries.
- Enable exception mode to catch database errors clearly.
- Validate and sanitize input before sending it to the database.
Practice Exercises
- Write a prepared statement that selects a user by ID using a positional placeholder.
- Create an
INSERTquery with named placeholders for a products table containing name and price. - Build a search query using
LIKEand a prepared statement to find blog posts by title keyword.
Mini Project / Task
Build a simple user registration script that accepts name and email from a form, saves the data with a prepared statement, and then displays a success message.
Challenge (Optional)
Create a reusable PHP function that accepts SQL and parameter values, executes a prepared statement safely, and returns fetched results for SELECT queries.
Detailed Introduction
PHP security basics are the foundational practices used to protect web applications from common attacks such as cross-site scripting, SQL injection, session hijacking, insecure file uploads, and weak password handling. Security exists because PHP applications often process user input, connect to databases, manage logins, and display dynamic content in browsers. In real life, every login form, contact form, admin dashboard, payment page, and profile editor must treat user data as untrusted. A secure PHP application validates input, escapes output, uses safe database queries, stores passwords correctly, and protects sessions. Learning security early is important because insecure habits become difficult to fix later. Even a small mistake, such as echoing raw input or building SQL queries with string concatenation, can expose user data or allow attackers to take control of accounts.
Core Concepts & Sub-types
Input Validation
Validation checks whether data matches expected rules, such as email format, required length, numeric range, or allowed characters.
Output Escaping
Escaping makes unsafe data safe before displaying it in HTML. In PHP, htmlspecialchars() is commonly used to prevent XSS.
Prepared Statements
Prepared statements separate SQL logic from user data, preventing SQL injection. They should be used with PDO or MySQLi.
Password Security
Passwords should never be stored in plain text. Use password_hash() and password_verify().
Session Security
Sessions identify logged-in users. Secure settings, regeneration of session IDs, and proper logout help prevent hijacking.
File Upload Safety
Uploaded files must be restricted by type, size, and storage location. Never trust the original filename or extension alone.
Step-by-Step Explanation
Start by assuming every value from $_GET, $_POST, $_COOKIE, $_FILES, and $_SERVER may be malicious.
Step 1: Validate incoming data based on strict rules.
Step 2: Sanitize only when needed for a specific format.
Step 3: Use prepared statements for database work.
Step 4: Escape data when outputting to HTML using htmlspecialchars($value, ENT_QUOTES, 'UTF-8').
Step 5: Hash passwords with password_hash() before saving.
Step 6: Regenerate session IDs after login using session_regenerate_id(true).
Step 7: For uploads, check MIME type, extension, size, and move files outside the public web root if possible.
Comprehensive Code Examples
Basic example
$name = $_POST['name'] ?? '';
$safeName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
echo "Hello, " . $safeName;
?>Real-world example
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$email = $_POST['email'] ?? '';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
exit('Invalid email');
}
$stmt = $pdo->prepare('SELECT id, email FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
?>Advanced usage
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$password = $_POST['password'] ?? '';
$hash = password_hash($password, PASSWORD_DEFAULT);
if (password_verify($password, $hash)) {
session_regenerate_id(true);
$_SESSION['authenticated'] = true;
echo 'Secure login success';
}
}
?>Common Mistakes
- Mistake: Trusting form input directly.
Fix: Validate every field before use. - Mistake: Building SQL with string concatenation.
Fix: Use prepared statements with bound parameters. - Mistake: Displaying user input without escaping.
Fix: Usehtmlspecialchars()before output in HTML. - Mistake: Saving plain-text passwords.
Fix: Hash withpassword_hash().
Best Practices
- Follow the rule: validate input, escape output.
- Use PDO prepared statements everywhere.
- Regenerate session IDs after login and privilege changes.
- Set strong password rules and use PHP password APIs.
- Limit file upload size and allowed MIME types.
- Show generic error messages to users but log detailed errors securely.
Practice Exercises
- Create a form that accepts a username and safely displays it in HTML.
- Write a PHP script that validates an email address before querying a database with a prepared statement.
- Build a password registration script that hashes a password and a login script that verifies it.
Mini Project / Task
Build a secure contact form that validates name and email, escapes displayed values, and stores submissions in a database using prepared statements.
Challenge (Optional)
Create a secure profile photo upload feature that accepts only image files, renames uploads safely, limits file size, and blocks dangerous extensions.
Detailed Introduction
Password hashing is the process of transforming a plain-text password into a fixed-length, unreadable string so the original password is not stored directly in a database.
It exists to protect user accounts if a database is leaked or stolen. In real applications such as e-commerce stores, banking dashboards, school portals, and admin panels, passwords must never be saved as plain text. Instead, PHP provides secure built-in tools like password_hash() and password_verify() to hash and verify passwords safely.
Unlike encryption, hashing is designed to be one-way. That means you do not ādecryptā a password later. When a user logs in, you hash-check the entered password against the stored hash. This approach greatly reduces damage during data breaches and is a core part of secure authentication systems.
Core Concepts & Sub-types
Hashing
A one-way conversion of a password into a secure string.
Salt
Modern PHP hashing automatically includes a random salt, which makes identical passwords produce different hashes.
Algorithms
PHP commonly uses PASSWORD_BCRYPT and PASSWORD_ARGON2ID. Argon2id is modern and strong when supported; bcrypt is widely compatible.
Verification
password_verify() compares a plain password with a stored hash securely.
Rehashing
password_needs_rehash() helps upgrade old hashes when you change algorithm settings.
Step-by-Step Explanation
To hash a password, first collect the user password from a form. Next, pass it to password_hash(). Store the returned hash in the database, not the original password.
During login, fetch the stored hash for that user. Then use password_verify($plainPassword, $storedHash). If it returns true, the password is valid.
Basic syntax:$hash = password_hash($password, PASSWORD_DEFAULT);if (password_verify($loginPassword, $hash)) { ... }PASSWORD_DEFAULT tells PHP to use the current recommended algorithm.
Comprehensive Code Examples
Basic example
$password = "MySecret123";
$hash = password_hash($password, PASSWORD_DEFAULT);
echo $hash;
if (password_verify("MySecret123", $hash)) {
echo "Password is correct";
} else {
echo "Invalid password";
}
?>Real-world example
// Registration
$email = $_POST['email'];
$password = $_POST['password'];
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// Save $email and $hashedPassword into database
// Login
$loginPassword = $_POST['password'];
$storedHash = $user['password']; // fetched from database
if (password_verify($loginPassword, $storedHash)) {
$_SESSION['user_id'] = $user['id'];
echo "Login successful";
} else {
echo "Incorrect credentials";
}
?>Advanced usage
$options = ['cost' => 12];
$hash = password_hash("AdminPass456", PASSWORD_BCRYPT, $options);
if (password_verify("AdminPass456", $hash)) {
if (password_needs_rehash($hash, PASSWORD_BCRYPT, $options)) {
$hash = password_hash("AdminPass456", PASSWORD_BCRYPT, $options);
// Update new hash in database
}
echo "Verified and checked for rehash";
}
?>Common Mistakes
- Saving plain-text passwords: Always store only the hash.
- Using MD5 or SHA1 directly: These are too fast and unsafe for passwords; use
password_hash(). - Comparing hashes manually: Use
password_verify()instead of simple string comparison. - Forgetting rehash upgrades: Check old hashes with
password_needs_rehash().
Best Practices
- Use
PASSWORD_DEFAULTunless you have a specific reason to choose another supported algorithm. - Hash passwords immediately before saving them.
- Never email or log passwords.
- Use HTTPS so passwords are protected in transit.
- Combine password hashing with rate limiting, strong password rules, and secure sessions.
Practice Exercises
- Create a PHP script that hashes a hard-coded password and prints the result.
- Build a second script that verifies an entered password against a stored hash.
- Modify your script to check whether a stored hash needs rehashing with a stronger cost value.
Mini Project / Task
Build a simple registration and login flow that stores a hashed password during signup and verifies it during login.
Challenge (Optional)
Create a login system that automatically rehashes the user password after successful login if the stored hash uses outdated settings.
Detailed Introduction
SQL injection is a security vulnerability that happens when untrusted user input is inserted directly into an SQL query. Attackers exploit this by injecting SQL code into form fields, URLs, search boxes, or API parameters. The goal may be to bypass login systems, read private data, modify records, or even delete tables. In real applications such as e-commerce sites, admin dashboards, and user portals, this is one of the most dangerous web security issues because databases often store passwords, orders, and personal details. In PHP, SQL injection usually appears when developers build queries with string concatenation instead of using safe database features. Preventing it is essential for every PHP developer because even a small login form can become a serious attack point if input is not handled correctly.
Core Concepts & Sub-types
Unsafe Query Concatenation
This happens when variables are directly added into SQL strings using quotes and concatenation. It is the main cause of SQL injection.
Prepared Statements
Prepared statements separate SQL structure from user data. The database treats input as data only, not executable SQL. This is the primary defense.
Parameter Binding
Binding values to placeholders like ? or named parameters such as :email ensures values are safely escaped and typed.
Input Validation
Validation checks whether input matches expected formats, such as integer IDs or valid emails. Validation does not replace prepared statements, but it reduces bad data and logic errors.
Least Privilege
Your database user should have only the permissions required by the app. If an attack happens, limited permissions reduce damage.
Step-by-Step Explanation
First, never build SQL like SELECT * FROM users WHERE email = '$email'. If a user submits malicious content, the query can change meaning. Instead, create a prepared statement. In PDO, write SQL with a placeholder such as SELECT * FROM users WHERE email = :email. Next, call prepare() on the database connection. Then pass the actual value with execute(). The database engine keeps the SQL command separate from the input. For numeric values like IDs, also validate or cast them before using them in application logic. Finally, handle errors safely and avoid exposing raw SQL messages to users.
Comprehensive Code Examples
Basic example using PDO prepared statements:
$pdo = new PDO($dsn, $user, $pass);
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $_POST['email']]);
$user = $stmt->fetch();Real-world login example:
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$password = $_POST['password'] ?? '';
if ($email) {
$stmt = $pdo->prepare("SELECT id, password_hash FROM users WHERE email = :email LIMIT 1");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password_hash'])) {
echo "Login successful";
} else {
echo "Invalid credentials";
}
}Advanced example with typed binding using MySQLi:
$stmt = $mysqli->prepare("SELECT title, price FROM products WHERE category_id = ? AND price < ?");
$categoryId = (int) $_GET['category_id'];
$maxPrice = (float) $_GET['max_price'];
$stmt->bind_param("id", $categoryId, $maxPrice);
$stmt->execute();
$result = $stmt->get_result();Common Mistakes
- Mistake: Escaping input manually and thinking it is enough.
Fix: Always use prepared statements. - Mistake: Validating input but still concatenating SQL strings.
Fix: Validation and prepared statements should be used together. - Mistake: Showing raw database errors to users.
Fix: Log detailed errors privately and show generic messages publicly.
Best Practices
- Use PDO or MySQLi prepared statements for every dynamic query.
- Validate emails, integers, and dates before processing them.
- Use least-privilege database accounts instead of full admin access.
- Hash passwords with
password_hash()and verify withpassword_verify(). - Keep database errors out of public pages.
Practice Exercises
- Convert an unsafe query that searches for a username into a PDO prepared statement.
- Create a PHP script that safely fetches one product by numeric ID using validation and binding.
- Build a safe login lookup that accepts an email and checks whether the user exists.
Mini Project / Task
Build a secure search form for products where users can filter by category and maximum price using prepared statements and input validation.
Challenge (Optional)
Create a reusable PHP function that accepts SQL with parameters, executes it safely with PDO, and returns results while handling errors securely.
Detailed Introduction
Cross-Site Scripting, or XSS, happens when untrusted input is displayed in a web page without proper escaping, allowing a browser to treat data as executable code. In PHP applications, this often occurs when user-submitted values such as comments, search terms, profile names, or query parameters are printed directly into HTML. Attackers can inject JavaScript to steal sessions, modify page content, redirect users, or perform actions on behalf of victims. XSS exists because browsers trust HTML, JavaScript, and attributes rendered by the server. Preventing XSS is essential in login systems, comment sections, admin dashboards, e-commerce forms, and any page that displays dynamic content.
Core Concepts & Sub-types
Stored XSS
Malicious code is saved in a database, then shown to other users later. Example: a comment field stores a script tag and renders it on a blog post.
Reflected XSS
The payload comes from the current request, such as a URL parameter, and is immediately echoed into the page. Example: showing an unescaped search query in results.
DOM-Based XSS
The browser-side JavaScript inserts unsafe data into the page. Even in PHP projects, front-end scripts can create this issue if they use dangerous methods like unsafe HTML insertion.
Output Escaping
The main defense is escaping data for the correct output context. In PHP, htmlspecialchars() is commonly used for HTML text and attributes.
Step-by-Step Explanation
First, treat all user input as untrusted, even if it comes from your own database. Second, validate input for business rules, such as allowed length or format. Third, escape output at the moment you display it. For normal HTML content in PHP, use htmlspecialchars($value, ENT_QUOTES, 'UTF-8'). ENT_QUOTES escapes both single and double quotes, which is important for attributes. 'UTF-8' ensures correct character handling. Fourth, avoid inserting raw user input into JavaScript, inline event handlers, style blocks, or URLs without context-specific protection. Fifth, add defense-in-depth with Content Security Policy, which reduces the impact of successful injection.
Comprehensive Code Examples
Basic example:
<?php
$name = $_GET['name'] ?? '';
echo '<h1>Hello, ' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</h1>';Real-world example:
<?php
$comment = $row['comment'];
?>
<div class="comment">
<p><?= htmlspecialchars($comment, ENT_QUOTES, 'UTF-8') ?></p>
</div>Advanced usage:
<?php
function e($value) {
return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}
$user = ['name' => $_POST['name'] ?? '', 'bio' => $_POST['bio'] ?? ''];
?>
<h2><?= e($user['name']) ?></h2>
<input type="text" value="<?= e($user['name']) ?>">
<p><?= e($user['bio']) ?></p>
<?php
header("Content-Security-Policy: default-src 'self'; script-src 'self'");
?>Common Mistakes
- Escaping input instead of output: store raw data when possible, then escape when rendering.
- Using the wrong context: HTML escaping is not enough for JavaScript, CSS, or URL contexts.
- Trusting database content: data from your database may still contain attacker input and must be escaped before display.
Best Practices
- Always use
htmlspecialchars()for HTML output. - Create a reusable helper like
e()to keep templates consistent. - Avoid inline JavaScript and unsafe HTML insertion patterns.
- Use Content Security Policy as an additional layer of protection.
- Sanitize rich HTML only with trusted libraries if users must submit formatted content.
Practice Exercises
- Create a PHP page that prints a query parameter safely inside an
h1element. - Build a small comment preview form that safely redisplays submitted text after POST.
- Make an input field that preserves the user value after validation failure without allowing XSS.
Mini Project / Task
Build a guestbook page where users submit their name and message, save them in an array or database, and render every entry safely using output escaping.
Challenge (Optional)
Create a reusable PHP escaping helper for HTML text and attributes, then refactor a multi-field form page so every displayed value is protected consistently.
Detailed Introduction
A simple login system allows users to enter credentials, verify identity, and access protected pages. In PHP, login systems are common in dashboards, e-commerce sites, school portals, admin panels, and membership platforms. The purpose is not just to let users in, but to control access securely. A basic login flow usually includes a form, server-side validation, password verification, session storage, and a logout process. In real life, even a small login feature teaches major backend concepts: handling form data, connecting to a database, hashing passwords, tracking logged-in users with sessions, and protecting private routes. This topic is foundational because many larger systems such as role-based access, profile pages, and password reset features are built on top of it.
Core Concepts & Sub-types
Login Form
An HTML form collects username or email and password, then sends data to PHP for processing.
Password Hashing
Passwords should never be stored as plain text. Use password_hash() to store and password_verify() to check them.
Sessions
PHP sessions store user login state between pages using $_SESSION after calling session_start().
Protected Pages
These are pages accessible only to authenticated users. If no valid session exists, the user is redirected.
Logout
Logout destroys the session so the user can no longer access protected content without logging in again.
Step-by-Step Explanation
Start by creating a users table with fields such as id, email, and password. Insert a user whose password is hashed. Next, build a login form with method=POST. In the processing script, read submitted values from $_POST, validate empty fields, then query the database for the matching email. If a record exists, use password_verify() to compare the entered password with the stored hash. If valid, start a session and save user data like $_SESSION['user_id'] and $_SESSION['email']. On protected pages, check whether the session variable exists. If not, redirect to the login page. Finally, create a logout file that clears and destroys the session. This structure is simple, readable, and suitable for beginners learning authentication basics.
Comprehensive Code Examples
Basic example:
<?php
session_start();
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$storedHash = password_hash('secret123', PASSWORD_DEFAULT);
if ($email === '[email protected]' && password_verify($password, $storedHash)) {
$_SESSION['email'] = $email;
echo 'Login successful';
} else {
echo 'Invalid credentials';
}Real-world example with database lookup:
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;dbname=app', 'root', '');
$stmt = $pdo->prepare('SELECT id, email, password FROM users WHERE email = ?');
$stmt->execute([$_POST['email']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($_POST['password'], $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['email'] = $user['email'];
header('Location: dashboard.php');
exit;
}
echo 'Login failed';Advanced usage for route protection and logout:
<?php
session_start();
function requireLogin() {
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
}
// dashboard.php
requireLogin();
echo 'Welcome ' . htmlspecialchars($_SESSION['email']);
// logout.php
session_unset();
session_destroy();
header('Location: login.php');
exit;Common Mistakes
- Storing plain-text passwords: Always hash passwords before saving them.
- Forgetting
session_start(): Without it, session variables will not work. - Using raw SQL with user input: Use prepared statements to prevent SQL injection.
- Not redirecting after login: Send users to a protected page after successful authentication.
Best Practices
- Use
password_hash()andpassword_verify()only, never custom encryption. - Validate and sanitize user input before processing.
- Escape output with
htmlspecialchars()when displaying user data. - Protect every restricted page with a reusable login-check function.
- Regenerate session IDs after login in production for stronger security.
Practice Exercises
- Create a login form that accepts email and password and prints an error if either field is empty.
- Store a hashed password in a variable and verify a typed password using
password_verify(). - Build a protected page that redirects guests to
login.phpif no session exists.
Mini Project / Task
Build a simple member area with three files: login.php, dashboard.php, and logout.php. After successful login, show the user email on the dashboard and block direct access for logged-out users.
Challenge (Optional)
Extend the login system so it tracks failed login attempts in a session variable and temporarily blocks access after three incorrect tries.
Detailed Introduction
A registration system allows users to create accounts in a web application by submitting details such as name, email, and password. It exists because most modern platforms need a way to identify users, personalize experiences, protect private data, and control access to features. In real life, registration systems are used in e-commerce sites, learning platforms, dashboards, forums, and SaaS applications. In PHP, building a registration system teaches several essential backend skills at once: handling form data, validating input, hashing passwords, preventing duplicate accounts, storing data in a database, and giving useful feedback to users. A good registration system is not just about saving a form; it is about security, reliability, and user experience. Beginners often start with a simple HTML form and a PHP script, but a professional implementation also checks request methods, sanitizes output, uses prepared statements, and stores passwords with strong hashing. This topic is important because it connects PHP fundamentals with real application development.
Core Concepts & Sub-types
Form Handling
PHP reads user-submitted values from $_POST when the form uses the POST method.
Validation
Validation ensures required fields are present, email format is correct, and passwords meet rules before saving data.
Password Hashing
Passwords must never be stored as plain text. Use password_hash() to create secure hashes.
Database Storage
User records are usually stored in MySQL using PDO or MySQLi with prepared statements to prevent SQL injection.
Duplicate Checking
Before inserting a new user, check whether the email already exists.
Step-by-Step Explanation
Start by creating an HTML form with fields like username, email, password, and confirm password. Set the form method to POST. In PHP, first check whether the request is POST using $_SERVER['REQUEST_METHOD'] === 'POST'. Next, read and trim values from $_POST. Then validate each field: make sure nothing important is empty, confirm the email is valid with filter_var(), and ensure both password fields match. If validation passes, hash the password using password_hash($password, PASSWORD_DEFAULT). After that, connect to the database and check if the email already exists. If not, insert the user using a prepared statement. Finally, show a success message or redirect the user to a login page. This flow is the foundation of most registration features in PHP applications.
Comprehensive Code Examples
Basic example:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$password = $_POST['password'];
if ($name === '' || $email === '' || $password === '') {
echo 'All fields are required.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email format.';
} else {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
echo 'Registration data is valid.';
}
}
?>Real-world example:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=app', 'root', '');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$check = $pdo->prepare('SELECT id FROM users WHERE email = ?');
$check->execute([$email]);
if ($check->fetch()) {
echo 'Email already registered.';
} else {
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare('INSERT INTO users (name, email, password) VALUES (?, ?, ?)');
$stmt->execute([$name, $email, $hash]);
echo 'User registered successfully.';
}
}
?>Advanced usage:
<?php
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$confirm = $_POST['confirm_password'];
if (strlen($name) < 3) $errors[] = 'Name must be at least 3 characters.';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Enter a valid email.';
if (strlen($password) < 8) $errors[] = 'Password must be at least 8 characters.';
if ($password !== $confirm) $errors[] = 'Passwords do not match.';
if (empty($errors)) {
$hash = password_hash($password, PASSWORD_DEFAULT);
echo 'Ready to save secure user record.';
}
}
?>Common Mistakes
Storing plain-text passwords instead of hashed passwords. Fix: always use
password_hash().Trusting user input without validation. Fix: validate required fields, email format, and password rules.
Using raw SQL with variables directly. Fix: use prepared statements with PDO or MySQLi.
Best Practices
Use POST for registration forms because sensitive data should not appear in the URL.
Hash passwords with
PASSWORD_DEFAULTfor modern security.Check for duplicate emails before inserting a user record.
Escape output when displaying user-provided values back in HTML.
Return clear error messages, but do not reveal sensitive system details.
Practice Exercises
Create a registration form with fields for name, email, and password, then display a message if any field is empty.
Add email validation and require the password to be at least 8 characters long.
Modify your script to compare password and confirm password before allowing registration.
Mini Project / Task
Build a PHP registration page that validates input, hashes the password, checks whether the email already exists, and inserts the new user into a MySQL database.
Challenge (Optional)
Extend the registration system so it preserves old form values after validation errors and displays all errors in a clean list above the form.
Detailed Introduction
A REST API is a way for applications to communicate over HTTP using predictable URLs, methods, and data formats. In PHP, REST APIs are commonly used to power mobile apps, JavaScript frontends, admin dashboards, payment integrations, and third-party services. Instead of returning full HTML pages, an API usually returns JSON so another system can read and use the data easily. REST exists to create a simple contract between client and server: the client sends a request, and the server returns data plus an HTTP status code. In real life, examples include fetching products from an online store, creating user accounts, updating profiles, or deleting tasks from a project manager app. Learning REST in PHP helps you move from traditional page rendering into backend service development, which is a core skill for modern web engineering.
Core Concepts & Sub-types
Resources
A resource is the thing your API manages, such as users, posts, or orders. Example endpoints include /users or /products/15.
HTTP Methods
GET reads data, POST creates data, PUT/PATCH updates data, and DELETE removes data. These methods tell the server what action the client wants.
Status Codes
Common codes include 200 for success, 201 for created, 400 for bad request, 404 for not found, and 500 for server error.
JSON
JSON is the standard response format for most REST APIs because it is lightweight and easy to parse in many languages.
Step-by-Step Explanation
In PHP, a basic REST endpoint usually starts by reading the request method with $_SERVER['REQUEST_METHOD']. Next, set the response content type using header('Content-Type: application/json'). Then inspect the URL or route, decide which resource is requested, and process input data if needed. For JSON input, read the raw body using file_get_contents('php://input') and convert it to an array using json_decode(..., true). Finally, send a JSON response with echo json_encode($data) and an appropriate status code using http_response_code().
Comprehensive Code Examples
Basic example:
<?php
header('Content-Type: application/json');
echo json_encode(['message' => 'Hello from PHP API']);Real-world example:
<?php
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
$users = [['id' => 1, 'name' => 'Ava'], ['id' => 2, 'name' => 'Noah']];
if ($method === 'GET') {
echo json_encode($users);
} else {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
}Advanced usage:
<?php
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);
if ($method === 'POST') {
if (!isset($input['title']) || trim($input['title']) === '') {
http_response_code(400);
echo json_encode(['error' => 'Title is required']);
exit;
}
http_response_code(201);
echo json_encode(['id' => 101, 'title' => $input['title']]);
} else {
http_response_code(405);
echo json_encode(['error' => 'Only POST allowed']);
}Common Mistakes
Returning plain text instead of JSON. Fix: always set the JSON header and use
json_encode().Ignoring HTTP status codes. Fix: use the correct code for success, validation failure, or missing data.
Reading POST data from
$_POSTwhen the client sends JSON. Fix: usephp://inputandjson_decode().
Best Practices
Use clear resource names such as
/usersand/orders.Keep responses consistent with keys like
message,data, anderror.Validate all incoming data before saving or processing it.
Separate routing, business logic, and database code as your API grows.
Practice Exercises
Create a PHP endpoint that returns a JSON object with your name, role, and current date.
Build a
GETendpoint that returns an array of three products in JSON format.Create a
POSTendpoint that accepts a JSON body with a task title and returns a created response.
Mini Project / Task
Build a simple task API in PHP with two endpoints: one GET route to list tasks and one POST route to add a new task from JSON input.
Challenge (Optional)
Extend your task API so that requesting /tasks/1 returns a single task and unknown task IDs return a 404 JSON error response.
Detailed Introduction
The final project is the capstone of the course, where you combine the most important PHP concepts into one complete application. Instead of practicing isolated topics such as forms, sessions, database queries, routing, and object-oriented code separately, this section shows how they work together in a real product. In professional development, final projects simulate actual business needs: users register, log in, submit data, view dashboards, and interact with a database securely. A strong PHP final project proves that you can move beyond syntax and build a maintainable web application. A practical example is a task manager, mini blog, or inventory tracker with authentication, CRUD operations, validation, and structured files. This kind of project reflects how PHP is used in startups, internal company tools, admin panels, content systems, and customer portals.
Core Concepts & Sub-types
Project Planning
Define features, user roles, pages, and data flow before coding.
Application Structure
Organize files into folders such as public, config, src, and views.
Database Integration
Use MySQL with PDO for secure queries, inserts, updates, and deletes.
Authentication & Security
Protect passwords with hashing, validate input, escape output, and manage sessions carefully.
CRUD Features
Create, read, update, and delete records as the heart of most PHP applications.
Step-by-Step Explanation
Step 1: Choose a realistic app, such as a task management system.
Step 2: List required features: registration, login, dashboard, add task, edit task, delete task, logout.
Step 3: Design the database tables, for example users and tasks.
Step 4: Create a reusable database connection with PDO.
Step 5: Build authentication pages and session checks.
Step 6: Implement CRUD operations with prepared statements.
Step 7: Separate business logic from HTML output for cleaner code.
Step 8: Test edge cases, invalid form input, duplicate emails, unauthorized access, and missing records.
Step 9: Refactor repeated code into functions or classes.
Step 10: Prepare the project for deployment with environment-based configuration.
Comprehensive Code Examples
Basic project database connection:
<?php
$pdo = new PDO("mysql:host=localhost;dbname=task_app", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);Real-world example: creating a task securely:
<?php
session_start();
require "db.php";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$title = trim($_POST["title"] ?? "");
$userId = $_SESSION["user_id"] ?? 0;
if ($title !== "" && $userId) {
$stmt = $pdo->prepare("INSERT INTO tasks (user_id, title) VALUES (?, ?)");
$stmt->execute([$userId, $title]);
}
}Advanced usage: reusable authorization helper:
<?php
function requireLogin(): void {
session_start();
if (!isset($_SESSION["user_id"])) {
header("Location: login.php");
exit;
}
}
function escape(string $value): string {
return htmlspecialchars($value, ENT_QUOTES, "UTF-8");
}Common Mistakes
- Mixing everything in one file: Split configuration, logic, and views into separate files.
- Using raw SQL with user input: Always use prepared statements with PDO.
- Skipping validation: Validate required fields, lengths, and data types before saving.
- Not protecting routes: Check sessions before allowing access to private pages.
Best Practices
- Start with a clear feature list and simple wireframe.
- Keep file structure organized and naming consistent.
- Reuse functions for repeated tasks such as redirects and escaping.
- Hash passwords with
password_hash()and verify withpassword_verify(). - Test the application one feature at a time before adding more complexity.
Practice Exercises
- Plan a mini PHP app and list at least five required features and two database tables.
- Create a folder structure for a final project using separate files for config, views, and processing logic.
- Build one secure CRUD feature, such as adding and listing records for logged-in users only.
Mini Project / Task
Build a simple PHP task manager where users can register, log in, add tasks, mark tasks complete, and delete their own tasks using a MySQL database.
Challenge (Optional)
Extend the project by adding task categories, due dates, and a filtered dashboard that shows completed and pending tasks separately.