Published , Last updated
If you’ve ever wondered how dynamic websites like Facebook, WordPress, or Wikipedia serve real-time content, PHP is a big part of that magic. PHP (Hypertext Preprocessor) is one of the most widely-used server-side scripting languages — and for good reason. Whether you're building a simple contact form or a large-scale content management system, PHP has the tools to get it done quickly and efficiently.
Despite the rise of newer technologies like Node.js and Python, PHP continues to dominate because:
Plus, shared hosting environments almost always support PHP out of the box, making deployment easy for solo developers and small businesses.
This guide is for:
Every great PHP application begins with understanding its core structure. Whether you're displaying a welcome message or processing a user form, all PHP code starts from the same basic building blocks.
<?php
echo "Hello, World!";
?>
Pro Tip from Experience: Always use <?php ... ?> tags (not short <? ... ?>) to ensure compatibility across all servers.
Save the file as index.php, place it in your htdocs (if using XAMPP), and open it in your browser:
http://localhost/index.php
<?php
$name = "Prakash";
echo "My name is $name.";
?>
// This is a single-line comment
# Also a single-line comment
/*
This is a multi-line comment
*/
In real projects, comments help teams understand your logic. I always encourage students to document key blocks during teaching.
Variables in PHP start with a $ sign.
$age = 25;
$name = "Sita";
$price = 99.99;
You don’t need to declare types — PHP is a loosely typed language.
PHP supports several data types. Here are the most commonly used:
Type | Example | Use Case |
---|---|---|
String | "Hello" | Text |
Integer | 123 | Whole numbers |
Float | 12.5 | Decimal numbers |
Boolean | true, false | Logic |
Array | ["apple", "banana"] | List of items |
Object | new ClassName() | OOP |
NULL | null | Empty/Undefined |
Resource | File handlers, DB connections | Advanced use |
PHP automatically converts types when needed.
$x = "10";
$y = 5;
echo $x + $y; // Outputs 15
This flexibility is useful, but can cause unexpected results. Always test your logic carefully, especially when working with forms.
Operators in PHP are symbols or keywords used to perform operations on variables and values — such as adding numbers, comparing values, or combining logic conditions.
In this section, we’ll break down the main types of operators with real-world examples and beginner-friendly explanations.
Used to perform basic math operations.
Operator | Name | Example | Result |
---|---|---|---|
+ | Addition | $a + $b | Sum |
- | Subtraction | $a - $b | Difference |
* | Multiplication | $a * $b | Product |
/ | Division | $a / $b | Quotient |
% | Modulus | $a % $b | Remainder |
Example:
$a = 10;
$b = 3;
echo $a + $b; // 13
echo $a % $b; // 1
I’ve used arithmetic operators often when calculating prices, discounts, or pagination logic in eCommerce and blog projects.
Used to assign values to variables.
Operator | Example | Meaning |
---|---|---|
= | $x = 5 | Assign 5 to $x |
+= | $x += 2 | $x = $x + 2 |
-= | $x -= 2 | $x = $x - 2 |
*= | $x *= 2 | $x = $x * 2 |
/= | $x /= 2 | $x = $x / 2 |
%= | $x %= 2 | $x = $x % 2 |
Used to compare values — commonly used in if statements and forms.
Operator | Meaning | Example | Result |
---|---|---|---|
== | Equal | $a == $b | true if equal |
=== | Identical (value + type) | $a === $b | true if type & value match |
!= | Not equal | $a != $b | true if different |
<> | Not equal | $a <> $b | Same as != |
!== | Not identical | $a !== $b | true if type/value differ |
> | Greater than | $a > $b | true if greater |
< | Less than | $a < $b | true if less |
>= | Greater or equal | $a >= $b | true if ≥ |
<= | Less or equal | $a <= $b | true if ≤ |
Example:
$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are too young.";
}
In form validation, I always use === to ensure exact matches between password fields.
Used to combine multiple conditions.
Operator | Meaning | Example |
---|---|---|
&& or and | Both must be true | $a > 5 && $b < 10 |
` | oror` | |
! | Not | !($a > 5) – true if $a <= 5 |
Example:
$loggedIn = true;
$isAdmin = false;
if ($loggedIn && $isAdmin) {
echo "Welcome, Admin!";
} else {
echo "Access Denied.";
}
This is something you can use in login systems, role management, and conditional display of content.
Quickly increase or decrease a variable’s value.
Operator | Meaning | Example |
---|---|---|
++$x | Pre-increment | Increments before use |
$x++ | Post-increment | Increments after use |
--$x | Pre-decrement | Decreases before use |
$x-- | Post-decrement | Decreases after use |
$x = 5;
echo ++$x; // 6
echo $x++; // 6 (but $x becomes 7 afterward)
A shorthand for if...else
$age = 20;
echo ($age >= 18) ? "Adult" : "Minor";
Clean and perfect for short decision-making tasks like UI messages.
Control structures in PHP let you make decisions and repeat actions. Whether you’re checking a user’s login status or looping through blog posts, you’ll use these structures all the time.
This section covers:
☑ Basic if...else Syntax:
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are underage.";
}
☑ elseif for Multiple Conditions:
$marks = 75;
if ($marks >= 90) {
echo "Grade A+";
} elseif ($marks >= 75) {
echo "Grade A";
} elseif ($marks >= 60) {
echo "Grade B";
} else {
echo "Needs Improvement";
}
I use elseif frequently in dashboards, filtering, and grading systems.
Perfect for checking one variable against many values.
$day = "Wednesday";
switch ($day) {
case "Monday":
echo "Start of the week.";
break;
case "Wednesday":
echo "Mid-week!";
break;
case "Friday":
echo "Weekend starts soon!";
break;
default:
echo "Just another day.";
}
Much cleaner than writing many if...elseif blocks when you're comparing a single value.
Loops are used to repeat code based on conditions — useful for listing users, posts, or items.
🔄 while Loop
$i = 1;
while ($i <= 5) {
echo "Number: $i <br>";
$i++;
}
🔄 do...while Loop
Ensures the loop runs at least once.
$i = 1;
do {
echo "Count: $i <br>";
$i++;
} while ($i <= 3);
I use this in admin panels when paginating — display content at least once even if fewer entries are there.
🔁 for Loop
Best when you know exactly how many times to run.
for ($i = 1; $i <= 5; $i++) {
echo "Item $i <br>";
}
🔁 foreach Loop
Specifically for arrays and objects.
$fruits = ["Apple", "Banana", "Mango"];
foreach ($fruits as $fruit) {
echo "$fruit <br>";
}
This is what I use 90% of the time while listing database results or working with APIs.
What Are Arrays in PHP?
An array is a special variable that holds multiple values at once. You can think of it like a list — of names, products, prices, users, anything.
PHP supports:
These use numeric keys starting from 0.
$colors = ["Red", "Green", "Blue"];
echo $colors[1]; // Green
Loop through indexed array:
foreach ($colors as $color) {
echo $color . "<br>";
}
Use this when looping through image galleries, product tags, form inputs, etc.
These use named keys instead of numbers.
$user = [
"name" => "Prakash",
"email" => "[email protected]",
"age" => 28
];
echo $user["email"]; // [email protected]
Loop through associative array:
foreach ($user as $key => $value) {
echo "$key: $value <br>";
}
⚡ This is my go-to structure when working with user profiles or config data.
An array inside another array — useful for complex data structures like tables or records.
$users = [
["name" => "Sita", "age" => 28],
["name" => "Ram", "age" => 32],
["name" => "Gita", "age" => 22]
];
echo $users[1]["name"]; // Ram
Loop through:
foreach ($users as $person) {
echo $person["name"] . " is " . $person["age"] . " years old.<br>";
}
⚡Multidimensional arrays are vital for managing database records, tables, and API responses.
Function | Purpose | Example Usage |
---|---|---|
count() | Count elements in an array | count($arr) |
array_push() | Add elements to the end | array_push($arr, "item") |
array_pop() | Remove last element | array_pop($arr) |
array_shift() | Remove first element | array_shift($arr) |
array_unshift() | Add elements to the beginning | array_unshift($arr, "item") |
array_merge() | Merge two or more arrays | array_merge($arr1, $arr2) |
array_slice() | Extract a slice of array | array_slice($arr, 1, 3) |
array_splice() | Remove/replace part of an array | array_splice($arr, 2, 1) |
array_keys() | Get all keys from an array | array_keys($arr) |
array_values() | Get all values from an array | array_values($arr) |
in_array() | Check if a value exists in an array | in_array("apple", $arr) |
array_key_exists() | Check if a key exists | array_key_exists("name", $arr) |
isset() | Check if a key is set and not null | isset($arr["name"]) |
array_search() | Search for a value and return its key | array_search("apple", $arr) |
array_map() | Apply a function to every element | array_map("strtoupper", $arr) |
array_filter() | Filter elements using a callback | array_filter($arr, fn($x) => $x > 5) |
array_reduce() | Reduce array to a single value | array_reduce($arr, fn($carry, $item) => $carry + $item) |
array_unique() | Remove duplicate values | array_unique($arr) |
array_reverse() | Reverse the array | array_reverse($arr) |
array_rand() | Pick one or more random keys | array_rand($arr) |
array_column() | Return values from a single column | array_column($users, "email") |
array_combine() | Combine two arrays (keys + values) | array_combine($keys, $values) |
array_diff() | Compare arrays and return differences | array_diff($arr1, $arr2) |
array_intersect() | Compare arrays and return matches | array_intersect($arr1, $arr2) |
array_walk() | Apply a callback to each element | array_walk($arr, fn(&$v) => $v *= 2) |
Example:
$colors = ["Red", "Blue"];
if (in_array("Red", $colors)) {
echo "Red is in the list!";
}
Real Use Case Example:
$posts = [
["title" => "PHP Basics", "author" => "Sam"],
["title" => "Working with MySQL", "author" => "Rita"]
];
foreach ($posts as $post) {
echo "<h2>{$post['title']}</h2>";
echo "<p>By {$post['author']}</p>";
}
⚡This is the exact format you can use to render blog posts from a database or API.
What is a Function in PHP?
A function is a block of code you define once and use as many times as needed. PHP has:
Functions help avoid repeating code, improve readability, and encapsulate logic — all critical for professional development.
function greetUser($name) {
return "Hello, $name!";
}
echo greetUser("Aarav"); // Hello, Aarav!
⚡Real use: You can use such greeting functions in user dashboards or for email templates.
➡ Function with multiple parameters:
function add($a, $b) {
return $a + $b;
}
echo add(5, 3); // 8
➡ Default parameter values:
function greet($name = "Guest") {
return "Welcome, $name!";
}
function modify($num) {
$num += 10;
}
function modifyRef(&$num) {
$num += 10;
}
⚡Use pass by reference (&) when you want the original value to be updated.
5.4. Returning Arrays or Multiple Values
function userInfo() {
return ["name" => "Sita", "email" => "[email protected]"];
}
$user = userInfo();
echo $user["email"]; // [email protected]
Useful for one-off operations, especially in array_map, filter, or events.
$square = function($x) {
return $x * $x;
};
echo $square(5); // 25
Shorter syntax for closures:
$double = fn($n) => $n * 2;
I use arrow functions a lot inside array processing, especially with array_map or array_filter.
A function that calls itself — great for dealing with nested data or directory structures.
function factorial($n) {
if ($n <= 1) return 1;
return $n * factorial($n - 1);
}
Function | Purpose | Example |
---|---|---|
strlen() | Length of a string | strlen("Hello") |
strtolower() | Convert to lowercase | strtolower("PHP") |
strtoupper() | Convert to uppercase | strtoupper("php") |
strpos() | Find position of substring | strpos("Hello", "e") |
substr() | Extract part of a string | substr("Hello", 1, 3) |
date() | Get current date/time | date("Y-m-d") |
time() | Get current Unix timestamp | time() |
is_array() | Check if variable is array | is_array($x) |
isset() | Check if variable is set | isset($x) |
empty() | Check if variable is empty | empty($x) |
What is String Handling?
Strings are sequences of characters. PHP offers a rich set of string functions to manipulate text for:
$name = "Sita";
echo "Hello, $name!";
Function | Purpose | Example Usage |
---|---|---|
strlen() | Get string length | strlen("Hello") → 5 |
strtoupper() | Convert to uppercase | strtoupper("hello") → HELLO |
strtolower() | Convert to lowercase | strtolower("HELLO") → hello |
ucfirst() | Uppercase first letter | ucfirst("hello") → Hello |
ucwords() | Uppercase first letter of each word | ucwords("hello world") → Hello World |
trim() | Remove whitespace (start & end) | trim(" Hello ") → Hello |
ltrim() / rtrim() | Remove whitespace (left/right) | ltrim(" Hello") → Hello |
str_replace() | Replace text | str_replace("world", "PHP", $str) |
strpos() | Find position of substring | strpos("Hello", "e") → 1 |
substr() | Extract substring | substr("abcdef", 1, 3) → bcd |
explode() | Split string into array | explode(",", "a,b,c") → [a, b, c] |
implode() | Join array into string | implode("-", ["a", "b", "c"]) → a-b-c |
strrev() | Reverse a string | strrev("PHP") → PHP |
number_format() | Format numbers with commas | number_format(1000000) → 1,000,000 |
htmlspecialchars() | Prevent XSS (converts < and > etc.) | htmlspecialchars("<b>") → <b> |
Real Use Examples
➡ Capitalize names from form input:
$name = "prakash bhandari";
$name = ucwords(strtolower(trim($name))); // "Prakash Bhandari"
➡ Format currency:
$price = number_format(49999.99); // 49,999.99
➡ Safe output of HTML:
echo htmlspecialchars("<script>alert('Hi');</script>");
➡ Output:
<script>alert('Hi');</script>
String to array:
$tags = "php,html,css";
$arr = explode(",", $tags); // ["php", "html", "css"]
Array to string:
echo implode(" | ", $arr); // php | html | css
Used in tags, categories, CSV parsing, and filters.
If you're working with non-English characters (e.g. Nepali, Chinese), use:
mb_strlen($str);
mb_substr($str, 0, 10);
⚡Why? strlen("राम") may return 6 instead of 2 — mb_strlen() solves this.
$userInput = strip_tags($_POST["comment"]);
$safeOutput = htmlspecialchars($userInput);
Superglobals are built-in variables in PHP that are accessible from anywhere in your script — no need to use global or pass them as arguments.
They are essential for handling:
📜 List of Common PHP Superglobals
Superglobal | Description |
---|---|
$_GET | Data sent via URL query string |
$_POST | Data sent via HTML form using POST |
$_REQUEST | Combined data from $_GET, $_POST, and $_COOKIE |
$_SERVER | Info about headers, path, script locations, etc. |
$_SESSION | Store user data across pages |
$_COOKIE | Small data stored in browser |
$_FILES | File uploads |
$_ENV | Environment variables |
$_GLOBALS | Access all global variables |
// URL: example.com/page.php?name=Sita
echo $_GET["name"]; // Outputs: Sita
⚡Use $_GET for search forms, pagination, filters, etc.
<form method="post">
<input type="text" name="email">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo $_POST["email"];
}
⚡Use this in contact forms, login systems, comments, etc.
$name = $_REQUEST["name"]; // Can be from GET or POST
⚠️ Not recommended for security-critical operations. Prefer $_POST or $_GET directly.
Key | Description |
---|---|
$_SERVER["PHP_SELF"] | Current script filename |
$_SERVER["HTTP_HOST"] | Hostname of the page |
$_SERVER["REQUEST_URI"] | URI of current page |
$_SERVER["REQUEST_METHOD"] | GET or POST |
$_SERVER["REMOTE_ADDR"] | Visitor’s IP Address |
Example:
echo $_SERVER["REQUEST_URI"]; // /blog?id=5
session_start();
$_SESSION["user"] = "Ram";
echo $_SESSION["user"]; // Ram
⚡Use sessions to store login status and flash messages.
setcookie("theme", "dark", time() + (86400 * 30)); // 30 days
echo $_COOKIE["theme"];
⚡ Cookies are used for "remember me", themes, preferences.
<form method="post" enctype="multipart/form-data">
<input type="file" name="photo">
<input type="submit">
</form>
<?php
$filename = $_FILES["photo"]["name"];
$tmpName = $_FILES["photo"]["tmp_name"];
move_uploaded_file($tmpName, "uploads/" . $filename);
⚡You can use this for profile picture uploads, post images, etc.
Often used with .env files or system configs:
echo $_ENV["APP_ENV"]; // development / production
PHP provides a rich set of built-in functions to interact with the file system — whether you're saving logs, uploading user images, exporting CSV data, or reading content from a text file.
Method 1: Read Entire File :
Sometimes, you just want to load the entire file content—say a markdown post or a log file.
$content = file_get_contents("notes.txt");
echo $content;
⚡It's a one-liner that works like magic when you're dealing with static content.
Method 2: Read Line-by-Line:
When working with large files (think logs or CSVs), reading line-by-line saves memory.
$handle = fopen("sample.txt", "r");
while (!feof($handle)) {
$line = fgets($handle);
echo $line . "<br>";
}
fclose($handle);
⚡Pro tip: Always fclose() to free resources.
Overwrite File Content:
file_put_contents("log.txt", "New log entry at " . date('Y-m-d H:i:s'));
Append to File:
file_put_contents("log.txt", "Another entry\n", FILE_APPEND);
Or, the manual way:
$handle = fopen("log.txt", "a");
fwrite($handle, "Appended line at " . date('H:i:s') . "\n");
fclose($handle);
⚡Use case: I use append mode for writing error logs or chat transcripts without wiping previous content.
Avoid "file not found" errors:
if (file_exists("data.txt")) {
echo file_get_contents("data.txt");
} else {
echo "File not found.";
}
⚡Best practice: Always check existence before reading or deleting.
if (file_exists("oldfile.txt")) {
unlink("oldfile.txt");
echo "File deleted!";
}
⚡Use case: Run this during cleanup routines for temporary or outdated files.
Create a New Folder
mkdir("newfolder");
List Files in Directory
$files = scandir("uploads/");
print_r($files);
This includes "." and "..", so you may want to filter those out.
HTML Upload Form:
<form method="POST" enctype="multipart/form-data">
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
PHP Upload Script:
if ($_FILES["myfile"]["error"] === 0) {
$filename = $_FILES["myfile"]["name"];
$tempPath = $_FILES["myfile"]["tmp_name"];
move_uploaded_file($tempPath, "uploads/" . $filename);
echo "File uploaded successfully!";
}
Validate File Type:
$allowed = ["jpg", "png", "pdf"];
$ext = pathinfo($_FILES["myfile"]["name"], PATHINFO_EXTENSION);
if (!in_array(strtolower($ext), $allowed)) {
die("Invalid file type");
}
Limit File Size:
if ($_FILES["myfile"]["size"] > 2 * 1024 * 1024) { // 2MB
die("File too large");
}
Rename to Prevent Overwrites:
$newName = time() . "_" . basename($_FILES["myfile"]["name"]);
move_uploaded_file($_FILES["myfile"]["tmp_name"], "uploads/" . $newName);
⚡Note: Never trust file names from users. Always sanitize or rename.
Every interactive website needs forms — for login, contact, registration, search, etc. But badly handled user input can lead to bugs, spam, or even security vulnerabilities like XSS and SQL injection.
In this section, you’ll learn how to:
<form method="post" action="">
Name: <input type="text" name="username"><br>
Email: <input type="email" name="email"><br>
<input type="submit">
</form>
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"];
$email = $_POST["email"];
echo "Name: $name <br> Email: $email";
}
⌛ This works, but it’s not safe yet.
$name = htmlspecialchars(trim($_POST["username"]));
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
Method | Purpose |
---|---|
trim() | Removes whitespace |
htmlspecialchars() | Prevents HTML/script injection |
filter_var() | Applies specific sanitization |
$errors = [];
if (empty($name)) {
$errors[] = "Name is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
if (count($errors)) {
foreach ($errors as $error) {
echo "<p style='color:red;'>$error</p>";
}
} else {
echo "Form submitted successfully.";
}
<?php
$name = $email = "";
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars(trim($_POST["username"]));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
if (empty($name)) {
$errors[] = "Name is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Valid email is required.";
}
if (empty($errors)) {
echo "Welcome, $name! We will contact you at $email.";
}
}
?>
<input type="text" name="username" value="<?= htmlspecialchars($name) ?>">
⚡Preserve user input in forms to improve UX and avoid frustration after validation fails.
Mistake | Secure Solution |
---|---|
Printing raw user input | Use htmlspecialchars() |
Using input in SQL directly | Use prepared statements |
Accepting unchecked emails/passwords | Validate with filter_var() |
Trusting input file names | Use basename() and sanitize |
PHP is a stateless language — but with sessions and cookies, you can retain data across multiple pages. This is essential for:
🚀 Starting and Using a Session
session_start(); // Must be at the top
$_SESSION["username"] = "Ram";
echo $_SESSION["username"]; // Ram
⚡Use this on admin dashboards to remember login status.
❌ Destroying a Session (Logout)
session_start();
session_unset(); // Removes all session variables
session_destroy(); // Destroys session data
Creating and Reading Cookies
// Set cookie for 30 days
setcookie("theme", "dark", time() + (86400 * 30));
echo $_COOKIE["theme"]; // Outputs: dark
🔒 Secure Cookie Example
setcookie("secure_login", "1", time()+3600, "/", "", true, true);
⚡The last true, true enables secure and HTTP-only flags
Use Case | Solution |
---|---|
Keep user logged in | $_SESSION["user_id"] |
Show "Welcome, [Name]" | Store $_SESSION["username"] |
Flash messages (e.g. "Saved!") | Set session then destroy after use |
Dark mode / Language choice | Save in a $_COOKIE |
Feature | Session | Cookie |
---|---|---|
Stored where? | Server | Browser |
Secure? | More secure | Less secure |
Expires? | When browser closes (default) | Based on expiration time |
Use case | Login, flash messages, carts | Theme, remember-me, language |
// On form submit
session_start();
$_SESSION["flash"] = "Post saved successfully!";
header("Location: dashboard.php");
// On dashboard.php
session_start();
if (isset($_SESSION["flash"])) {
echo "<p>" . $_SESSION["flash"] . "</p>";
unset($_SESSION["flash"]);
}
⚡ Flash messages show once and disappear.
Every PHP developer — from beginner to pro — deals with errors, warnings, and bugs. Instead of ignoring them, learn to handle them gracefully using proper techniques like:
ini_set('display_errors', 1);
error_reporting(E_ALL);
⚡Add this at the top during testing.
ini_set("log_errors", 1);
ini_set("error_log", "logs/php-error.log");
// Now errors go to logs/php-error.log
function customError($errno, $errstr) {
echo "Oops! [$errno] $errstr<br>";
}
set_error_handler("customError");
// Trigger error
echo 10 / 0;
Lets you format or log errors your way
try {
if (!file_exists("data.csv")) {
throw new Exception("File not found!");
}
} catch (Exception $e) {
echo "Caught Exception: " . $e->getMessage();
}
⚡ Best practice for file operations, external APIs, and user authentication
Error Type | Description |
---|---|
Notice | Minor errors, like using undefined variable |
Warning | Non-fatal issues, script continues |
Fatal Error | Stops the script |
Parse Error | Syntax issue, fails to compile |
Exception | Thrown via throw, caught with try |
$users = ["admin", "editor", "guest"];
var_dump($users);
print_r($users);
Function | Usage |
---|---|
var_dump() | Shows type + value |
print_r() | More readable for arrays |
error_reporting(E_ERROR | E_WARNING | E_PARSE);
Constant | Shows |
---|---|
E_ALL | All errors and warnings |
E_ERROR | Fatal errors |
E_WARNING | Runtime warnings |
E_NOTICE | Minor notices |
OOP (Object-Oriented Programming) in PHP helps you organize your code better, reuse components, and build scalable applications like CMSs, eCommerce platforms, or frameworks (like Laravel).
If you’ve worked with C or Java, some concepts will feel familiar.
OOP is a way of structuring code using:
class Car {
public $brand = "Toyota";
public function drive() {
echo "Driving a " . $this->brand;
}
}
$myCar = new Car();
$myCar->drive(); // Driving a Toyota
⚡$this refers to the current object.
class User {
public $name;
function __construct($name) {
$this->name = $name;
}
function greet() {
return "Hello, " . $this->name;
}
}
$user1 = new User("Ram");
echo $user1->greet(); // Hello, Ram
⚡ This is useful for setting initial values.
Feature | Purpose | Example |
---|---|---|
Encapsulation | Group related data/functions in one class | ✔️ |
Inheritance | Extend a class using extends | ✔️ |
Polymorphism | Use the same method name in different classes | ✔️ |
Abstraction | Hide internal details via abstract classes | ✔️ |
class Animal {
public function sound() {
return "Some sound";
}
}
class Dog extends Animal {
public function sound() {
return "Bark";
}
}
$dog = new Dog();
echo $dog->sound(); // Bark
⚡ Method overriding in action.
Modifier | Meaning |
---|---|
public | Accessible anywhere |
protected | Accessible in class and subclasses |
private | Only in the current class |
class MathHelper {
public static $pi = 3.14159;
public static function square($n) {
return $n * $n;
}
}
echo MathHelper::$pi; // 3.14159
echo MathHelper::square(5); // 25
⚡No need to create an object
interface Shape {
public function getArea();
}
class Circle implements Shape {
public function getArea() {
return 3.14 * 5 * 5;
}
}
⚡Interface defines what must be implemented, not how.
abstract class Payment {
abstract public function process();
}
class PayPal extends Payment {
public function process() {
return "Processing via PayPal";
}
}
⚡Cannot instantiate abstract class directly
PHP and MySQL are like best friends in web development. Almost every dynamic website needs to store and retrieve data — and PHP connects seamlessly to MySQL using either MySQLi or PDO.
Using MySQLi (Object-Oriented):
$mysqli = new mysqli("localhost", "root", "password", "my_database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
Using PDO (PHP Data Objects):
try {
$pdo = new PDO("mysql:host=localhost;dbname=my_database", "root", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
⚡Tip: Use PDO if you want to support multiple databases (MySQL, PostgreSQL, SQLite, etc.)
MySQLi:
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')";
$mysqli->query($sql);
PDO:
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')";
$pdo->exec($sql);
MySQLi:
$result = $mysqli->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo $row["name"] . "<br>";
}
PDO:
$stmt = $pdo->query("SELECT * FROM users");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row["name"] . "<br>";
}
$sql = "UPDATE users SET name='Jane' WHERE id=1";
$mysqli->query($sql); // MySQLi
$pdo->exec($sql); // PDO
$sql = "DELETE FROM users WHERE id=1";
$mysqli->query($sql); // MySQLi
$pdo->exec($sql); // PDO
They prevent attackers from injecting SQL via form inputs (e.g., login form or search box).
MySQLi Prepared Statement:
$stmt = $mysqli->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email); // "s" = string
$email = $_POST["email"];
$stmt->execute();
$result = $stmt->get_result();
PDO Prepared Statement:
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $_POST["email"]]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
🔐 Always use prepared statements for user inputs (e.g., login, signup, comments).
PHP comes with a rich set of built-in functions that simplify everything from working with dates to sending HTTP requests. In this section, you’ll learn how to use some of the most commonly needed tools in real-world PHP development.
Get Current Date and Time:
echo date("Y-m-d H:i:s"); // Output: 2025-04-29 14:35:00
Convert String to Timestamp:
echo strtotime("next Monday"); // Output: Unix timestamp
Format a Timestamp:
echo date("l, d M Y", strtotime("2025-04-29")); // Output: Tuesday, 29 Apr 2025
Time Difference:
$start = strtotime("2025-04-01");
$end = strtotime("2025-04-10");
$diff = ($end - $start) / (60 * 60 * 24);
echo "Difference in days: $diff";
APIs, AJAX, and frontend-backend communication often rely on JSON.
Encode Array to JSON:
$data = ["name" => "John", "email" => "[email protected]"];
$json = json_encode($data);
echo $json;
Output: {"name":"John","email":"[email protected]"}
Decode JSON to PHP Array:
$json = '{"name":"John","email":"[email protected]"}';
$data = json_decode($json, true); // true for associative array
echo $data["email"]; // Output: [email protected]
🔒 Always validate JSON from external sources before decoding.
cURL is a powerful way to send HTTP requests from PHP (e.g., fetch data from an API).
Basic GET Request:
$ch = curl_init("https://api.example.com/data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
print_r($data);
POST Request Example:
$ch = curl_init("https://api.example.com/submit");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(["name" => "John"]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
🔐 Use CURLOPT_HTTPHEADER to send tokens or content types.
Whether you’re working on e-commerce discounts or graphics, PHP math functions are useful.
Function | Description | Example |
---|---|---|
abs() | Absolute value | abs(-10) → 10 |
round() | Round a number | round(4.6) → 5 |
ceil() | Round up | ceil(4.1) → 5 |
floor() | Round down | floor(4.9) → 4 |
rand() | Random number | rand(1, 100) |
max()/min() | Highest or lowest value from list | max(1,2,3) → 3 |
sqrt() | Square root | sqrt(16) → 4 |
pow() | Power | pow(2, 3) → 8 |
Sending emails in PHP can be done using the built-in mail() function or the more powerful and reliable PHPMailer for SMTP-based emails.
$to = "[email protected]";
$subject = "Welcome to our site!";
$message = "Thank you for registering.";
$headers = "From: [email protected]";
mail($to, $subject, $message, $headers);
Limitations:
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: [email protected]";
$message = "<h1>Thank You!</h1><p>We appreciate your registration.</p>";
mail($to, $subject, $message, $headers);
Step 1: Install via Composer
composer require phpmailer/phpmailer
Step 2: PHP Script Example
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_app_password'; // Use App Password, not Gmail login
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'User');
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = '<b>This is the HTML message body</b>';
$mail->AltBody = 'This is the plain text version';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
$mail->addAttachment('/path/to/file.pdf'); // Optional
Security is not optional when building real-world applications. Whether it's a login form, blog CMS, or an API, neglecting security can lead to data leaks, defacement, or worse.
This section will walk you through the must-know security techniques every PHP developer — beginner or professional — should follow.
SQL Injection is one of the most common and dangerous attacks. It occurs when user inputs are directly inserted into SQL queries.
❌ Vulnerable Example:
// DO NOT USE
$sql = "SELECT * FROM users WHERE email = '" . $_POST['email'] . "'";
➡ Safe With Prepared Statements (PDO):
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $_POST['email']]);
➡ Safe With MySQLi :
$stmt = $mysqli->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $_POST['email']);
$stmt->execute();
⚡Rule: Never trust user input. Always use prepared statements.
XSS allows attackers to inject malicious JavaScript into your pages, often via comment forms, search inputs, etc.
❌ Vulnerable Code:
echo $_GET['username'];
➡ Sanitize Output with htmlspecialchars() :
echo htmlspecialchars($_GET['username'], ENT_QUOTES, 'UTF-8');
➡ Escape Data Before Displaying in HTML:
<input type="text" value="<?php echo htmlspecialchars($value); ?>">
Use frameworks (like Laravel or Twig) that auto-escape HTML output by default.
Plain text passwords? NEVER. PHP provides secure and modern password hashing tools.
➡ Hash Password Before Storing:
$hash = password_hash("userpassword", PASSWORD_DEFAULT);
PASSWORD_DEFAULT uses bcrypt (secure and recommended).
➡ Verify Password on Login:
if (password_verify($_POST['password'], $hashFromDatabase)) {
echo "Login successful!";
}
⚡password_hash() automatically generates a salt, so don’t use md5() or sha1() — they are insecure and outdated.
Even if your site uses secure code, if data is transmitted over HTTP, it’s vulnerable to man-in-the-middle attacks.
➡ Always Use HTTPS:
➡ Secure Sessions:
session_start();
// Regenerate session ID to prevent session fixation
session_regenerate_id(true);
// Set secure session cookie parameters
session_set_cookie_params([
'lifetime' => 0,
'secure' => true, // Only over HTTPS
'httponly' => true, // JavaScript can't access
'samesite' => 'Strict'
]);
🔐 Combine this with login checks and access controls.
For developers stepping into production-level PHP development, performance, scalability, and clean code structure become top priorities. This section is crafted with professional developers in mind — offering battle-tested tips and tools that elevate your PHP game.
Fast code = happy users. Here are practical ways to make your PHP run faster:
➡ Use Output Buffering:
ob_start();
// Your HTML/PHP here
ob_end_flush();
Improves performance by reducing I/O operations and allowing compression.
➡ Avoid Repeated Database Queries:
// Instead of multiple queries in a loop:
$results = $pdo->query("SELECT * FROM users")->fetchAll();
Tip: Use joins and in-memory caching wherever possible.
➡ Use isset() Instead of array_key_exists() :
// Faster
if (isset($array['key'])) {}
// Slower
if (array_key_exists('key', $array)) {}
➡ Use Native PHP Functions:
Native functions are highly optimized C code. For example:
$sum = array_sum($numbers); // Faster than manual loops
Composer is the de facto standard for managing packages/libraries in PHP.
➡ Initialize Composer in a Project:
composer init
➡ Install a Package (e.g., Guzzle HTTP client):
composer require guzzlehttp/guzzle
➡ Load Composer’s Autoloader in Your PHP:
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
💼 Composer is used in frameworks like Laravel, Symfony, and in most modern PHP projects.
Autoloading helps load classes automatically, instead of manually including files.
➡ PSR-4 Autoloading via Composer:
In composer.json:
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
Then run:
composer dump-autoload
Now your file src/Controller/HomeController.php can be auto-loaded using:
use App\Controller\HomeController;
No more manual require statements — keeps code clean and modular.
18.4 Namespaces – Avoid Class Conflicts
Namespaces help avoid conflicts when multiple libraries have classes with the same name.
➡ Define a Namespace:
namespace App\Models;
class User {
// ...
}
➡ Use a Namespaced Class:
use App\Models\User;
$user = new User();
➡ Avoiding Conflicts in Big Projects:
Use namespaces like:
CompanyName\Module\Feature
A must for enterprise-level applications or when using multiple libraries.
Manual echo/var_dump can only take you so far. Use professional tools:
➡ Xdebug – Powerful Debugging & Profiling
Install via:
pecl install xdebug
Then configure php.ini:
zend_extension="xdebug.so"
xdebug.mode=debug
Works seamlessly with VS Code or PhpStorm.
➡ Alternatives:
PHP 8 introduced several powerful features that improve readability, developer productivity, and performance. Whether you're maintaining legacy code or writing fresh applications, understanding these additions is a must for modern PHP development.
Let's break down the key enhancements you should start using today.
Named arguments allow passing arguments to functions by specifying the parameter name, improving code clarity and flexibility.
Example:
function greet($name, $greeting = "Hello") {
return "$greeting, $name!";
}
// Traditional
echo greet("Alice", "Hi");
// PHP 8 Named Argument
echo greet(name: "Alice", greeting: "Hi");
⚡Especially useful when functions have many optional parameters.
The match expression is a more concise and safer alternative to switch.
Example:
$statusCode = 404;
echo match ($statusCode) {
200 => 'OK',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown',
};
Why It’s Better:
PHP 8 introduces attributes (like annotations in other languages) that let you attach metadata to classes, functions, and properties.
Example:
#[Route('/users', methods: ['GET'])]
function getUsers() {
// ...
}
Define custom attributes:
#[Attribute]
class Route {
public function __construct(public string $path, public array $methods = []) {}
}
⚡Used heavily in frameworks for routing, validation, and ORM mapping (like Symfony, Laravel, Doctrine).
No more nested if checks just to avoid null errors. The nullsafe operator helps safely access chained properties/methods.
Example:
// Without nullsafe operator
if ($user !== null && $user->profile !== null) {
echo $user->profile->bio;
}
// With nullsafe operator
echo $user?->profile?->bio;
⚡Cleaner, less error-prone code — especially in APIs, auth systems, or complex data structures.
PHP 8 introduced JIT compilation, which can improve performance by compiling parts of your PHP code to machine code at runtime.
➡ What It Means:
➡ Enable JIT (in php.ini):
opcache.enable=1
opcache.jit_buffer_size=100M
opcache.jit=tracing
➡ When You’ll See Gains:
Type of Task | Benefit From JIT? |
---|---|
Web API | Minimal |
Image processing | ☑ Yes |
Mathematical models | ☑ Yes |
Database queries | No (depends on DB) |
Use JIT when you process data-heavy tasks like video rendering, complex calculations, etc.
This comprehensive PHP Cheat Sheet for beginners and professionals is designed to guide you through every major PHP concept — from variables and arrays to databases, security, Composer, and PHP 8.x features — you now have a practical, go-to reference to support your development workflow.
This guide isn’t just theory — it’s packed with real-world examples and tips that you can apply immediately. Think of it as your personal PHP handbook — always ready when you need a refresher, a best practice, or a quick code snippet.
➡ If you found this guide helpful, don’t forget to bookmark it for future reference, share it with your friends, and leave a comment below with your thoughts or questions. Your feedback helps improve the resource for everyone.