01. 🚀 PHP Basics & Setup
PHP (Hypertext Preprocessor) is a widely-used open source server-side scripting language designed for web development. It was created by Rasmus Lerdorf in 1994 and has evolved into a powerful language powering over 75% of all websites.
Why Learn PHP?
PHP offers several advantages for web development:
1. Server-Side Execution: Code runs on server before sending to browser
2. Cross-Platform: Works on Windows, Linux, macOS
3. Open Source: Free with massive community support
4. Database Support: Excellent MySQL integration
5. Frameworks: Laravel, Symfony, CodeIgniter for rapid development
Setting Up PHP Environment
You need three main components to run PHP:
- Web Server: Apache or Nginx
- PHP Interpreter: Processes PHP code
- Database: MySQL/MariaDB (optional)
Example: First PHP Program
<!DOCTYPE html>
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<h1><?php echo "Hello, PHP World!"; ?></h1>
<?php
// Display server information
echo "<p>Today is: " . date("Y-m-d") . "</p>";
echo "<p>PHP Version: " . phpversion() . "</p>";
echo "<p>Server Software: " . $_SERVER['SERVER_SOFTWARE'] . "</p>";
// Simple calculation
$num1 = 15;
$num2 = 7;
$sum = $num1 + $num2;
echo "<p>Calculation: $num1 + $num2 = $sum</p>";
?>
</body>
</html>
Note: PHP files must have a .php extension and be executed on a web server with PHP support. You cannot run PHP files by simply opening them in a browser.
Hello, PHP World!
Today is: 2025-01-27
PHP Version: 8.1.0
Server Software: Apache/2.4.41
Calculation: 15 + 7 = 22
02. 📦 Variables & Data Types
PHP is a loosely typed language, meaning you don't need to declare variable types explicitly. Variables start with a dollar sign ($) followed by the variable name.
PHP Data Types
- String: Text data (single or double quotes)
- Integer: Whole numbers (positive or negative)
- Float: Decimal numbers
- Boolean:
trueorfalse - Array: Collection of values
- Object: Instance of a class
- NULL: Variable with no value
Variable Naming Rules
1. Starts with $ followed by name
2. Name must begin with letter or underscore
3. Can contain letters, numbers, underscores
4. Case-sensitive ($name ≠ $Name)
5. Cannot contain spaces or special characters
Example: Working with Variables
<?php
// String variables
$name = "John Doe";
$city = 'New York';
$greeting = "Hello, $name"; // Variable interpolation
// Integer variables
$age = 25;
$quantity = 100;
$temperature = -5;
// Float variables
$price = 19.99;
$pi = 3.14159;
$taxRate = 0.08;
// Boolean variables
$isLoggedIn = true;
$hasPermission = false;
// Array variables
$colors = array("red", "green", "blue");
$person = ["name" => "Alice", "age" => 30, "city" => "London"];
// NULL variable
$noValue = NULL;
// Output variables
echo "Name: $name<br>";
echo "Age: $age years<br>";
echo "Price: \$$price<br>";
echo "Logged in: " . ($isLoggedIn ? 'Yes' : 'No') . "<br>";
// Type checking
echo "Type of name: " . gettype($name) . "<br>";
echo "Type of age: " . gettype($age) . "<br>";
echo "Is array? " . (is_array($colors) ? 'Yes' : 'No') . "<br>";
// Constants (cannot be changed)
define("SITE_NAME", "MyWebsite");
const MAX_USERS = 100;
echo SITE_NAME . " can have " . MAX_USERS . " users.<br>";
// Variable variables
$category = "books";
$$category = "PHP Programming"; // Creates $books
echo "Category: $category, Value: $books<br>";
?>
03. 🔧 Operators & Control Flow
PHP supports various operators for performing operations on variables and values. Control flow statements allow your program to make decisions and execute different code paths.
Operator Types
- Arithmetic:
+ - * / % ** - Assignment:
= += -= *= /= - Comparison:
== === != !== < > <= >= - Logical:
&& || ! and or xor - String:
. .=(concatenation) - Increment/Decrement:
++ --
Conditional Statements
if: Execute code if condition is true
if...else: Alternative execution path
if...elseif...else: Multiple conditions
switch: Multiple choice selection
Ternary: ? : shorthand
Null Coalescing: ?? operator (PHP 7+)
Example: Operators & Control Flow
<?php
// Arithmetic operators
$a = 10;
$b = 3;
echo "Addition: " . ($a + $b) . "<br>";
echo "Subtraction: " . ($a - $b) . "<br>";
echo "Multiplication: " . ($a * $b) . "<br>";
echo "Division: " . ($a / $b) . "<br>";
echo "Modulus: " . ($a % $b) . "<br>";
echo "Exponent: " . ($a ** $b) . "<br>";
// Comparison operators
$x = 5;
$y = "5";
echo "x == y: " . ($x == $y) . "<br>"; // true (value comparison)
echo "x === y: " . ($x === $y) . "<br>"; // false (strict comparison)
// Logical operators
$hasAccount = true;
$isPremium = false;
if ($hasAccount && !$isPremium) {
echo "Free account user<br>";
}
if ($hasAccount || $isPremium) {
echo "Has access to basic features<br>";
}
// String concatenation
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo "Full Name: $fullName<br>";
// if-elseif-else statement
$score = 85;
if ($score >= 90) {
$grade = "A";
echo "Excellent!<br>";
} elseif ($score >= 80) {
$grade = "B";
echo "Good job!<br>";
} elseif ($score >= 70) {
$grade = "C";
echo "Fair.<br>";
} else {
$grade = "F";
echo "Needs improvement.<br>";
}
echo "Grade: $grade<br>";
// Switch statement
$day = "Monday";
switch($day) {
case "Monday":
echo "Start of work week<br>";
break;
case "Friday":
echo "Weekend is coming!<br>";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend!<br>";
break;
default:
echo "Regular day<br>";
}
// Ternary operator
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo "Status: $status<br>";
// Null coalescing operator
$username = $_GET['user'] ?? 'guest';
echo "Username: $username<br>";
// Spaceship operator (PHP 7+)
echo "1 <=> 1: " . (1 <=> 1) . "<br>"; // 0
echo "1 <=> 2: " . (1 <=> 2) . "<br>"; // -1
echo "2 <=> 1: " . (2 <=> 1) . "<br>"; // 1
?>
04. 🔁 Loops & Arrays
Loops execute a block of code repeatedly while a specified condition is true. Arrays store multiple values in a single variable and are essential for data manipulation in PHP.
Loop Types in PHP
- for: Count-controlled iteration
- while: Pre-test loop (check condition first)
- do...while: Post-test loop (execute at least once)
- foreach: Array iteration (specialized for arrays)
Array Types
Indexed Arrays: Numeric keys starting from 0
Associative Arrays: String keys (key-value pairs)
Multidimensional Arrays: Arrays within arrays
Array Functions: Built-in functions for array manipulation
Example: Loops & Arrays
<?php
// For loop
echo "Counting 1 to 5: ";
for($i = 1; $i <= 5; $i++) {
echo "$i ";
}
echo "<br>";
// While loop
echo "While loop countdown: ";
$count = 5;
while($count > 0) {
echo "$count ";
$count--;
}
echo "<br>";
// Do-while loop
echo "Do-while (executes at least once): ";
$num = 1;
do {
echo "$num ";
$num++;
} while($num <= 3);
echo "<br>";
// Indexed array
$colors = ["Red", "Green", "Blue", "Yellow"];
echo "Colors array: ";
foreach($colors as $color) {
echo "$color ";
}
echo "<br>";
// Associative array
$student = [
"name" => "Alice",
"age" => 22,
"grade" => "A",
"city" => "New York"
];
echo "Student information:<br>";
foreach($student as $key => $value) {
echo ucfirst($key) . ": $value<br>";
}
// Multidimensional array
$students = [
["name" => "John", "grade" => "A"],
["name" => "Sarah", "grade" => "B"],
["name" => "Mike", "grade" => "A"]
];
echo "<h4>Student List:</h4>";
foreach($students as $student) {
echo "Name: {$student['name']}, Grade: {$student['grade']}<br>";
}
// Array functions
$numbers = [5, 2, 8, 1, 9];
// Sorting
sort($numbers);
echo "Sorted numbers: " . implode(", ", $numbers) . "<br>";
// Array filtering
$evenNumbers = array_filter($numbers, function($num) {
return $num % 2 == 0;
});
echo "Even numbers: " . implode(", ", $evenNumbers) . "<br>";
// Array mapping
$squared = array_map(function($num) {
return $num * $num;
}, $numbers);
echo "Squared numbers: " . implode(", ", $squared) . "<br>";
// Array reduce (sum)
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
echo "Sum of numbers: $sum<br>";
// Array searching
$search = array_search(8, $numbers);
echo "Number 8 found at index: $search<br>";
// Array merging
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$merged = array_merge($array1, $array2);
echo "Merged array: " . implode(", ", $merged) . "<br>";
// Nested loops
echo "<h4>Multiplication Table (1-3):</h4>";
for($i = 1; $i <= 3; $i++) {
for($j = 1; $j <= 3; $j++) {
echo ($i * $j) . "\t";
}
echo "<br>";
}
?>
05. ⚙️ Functions & Forms
Functions allow you to group code into reusable blocks. Forms are essential for collecting user input in web applications. PHP handles form data through superglobal arrays.
Function Features
1. Parameters: Input values passed to function
2. Return Values: Value returned by function
3. Default Parameters: Optional arguments with default values
4. Variable Scope: Local vs global variables
5. Type Declarations: Type hints for parameters and return values (PHP 7+)
Form Handling
- GET Method: Data visible in URL (limited size)
- POST Method: Data hidden in request body (no size limit)
- Form Validation: Ensure data meets requirements
- Form Sanitization: Clean data to prevent security issues
Example: Functions & Form Handling
<?php
// Basic function
function greet($name) {
return "Hello, $name!";
}
echo greet("John") . "<br>";
// Function with default parameter
function calculateArea($length, $width = 10) {
return $length * $width;
}
echo "Area (default width): " . calculateArea(5) . "<br>";
echo "Area (custom width): " . calculateArea(5, 8) . "<br>";
// Function with type declarations (PHP 7+)
function addNumbers(int $a, int $b): int {
return $a + $b;
}
echo "Sum: " . addNumbers(5, 3) . "<br>";
// Function returning multiple values (using array)
function calculateStats($numbers) {
return [
'count' => count($numbers),
'sum' => array_sum($numbers),
'average' => array_sum($numbers) / count($numbers),
'min' => min($numbers),
'max' => max($numbers)
];
}
$nums = [10, 20, 30, 40, 50];
$stats = calculateStats($nums);
echo "Count: {$stats['count']}, Sum: {$stats['sum']}, Avg: {$stats['average']}<br>";
// Anonymous function (closure)
$multiply = function($x, $y) {
return $x * $y;
};
echo "Product: " . $multiply(4, 5) . "<br>";
// Variable-length arguments (PHP 5.6+)
function sumAll(...$numbers) {
return array_sum($numbers);
}
echo "Total: " . sumAll(1, 2, 3, 4, 5) . "<br>";
// ============================================
// FORM HANDLING EXAMPLE
// ============================================
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Sanitize input
$name = htmlspecialchars(trim($_POST['name'] ?? ''));
$email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
$age = intval($_POST['age'] ?? 0);
$message = htmlspecialchars(trim($_POST['message'] ?? ''));
// Validation
$errors = [];
if (empty($name)) {
$errors[] = "Name is required";
} elseif (strlen($name) < 2) {
$errors[] = "Name must be at least 2 characters";
}
if (empty($email)) {
$errors[] = "Email is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
if ($age < 1 || $age > 120) {
$errors[] = "Age must be between 1 and 120";
}
if (empty($message)) {
$errors[] = "Message is required";
} elseif (strlen($message) < 10) {
$errors[] = "Message must be at least 10 characters";
}
// If no errors, process form
if (empty($errors)) {
$success = true;
// In real application: save to database, send email, etc.
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
<style>
.container { max-width: 600px; margin: 20px auto; padding: 20px; }
.success { background: #d4edda; color: #155724; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
.error { background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input, textarea, select {
width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;
}
button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #0056b3; }
</style>
</head>
<body>
<div class="container">
<h2>Contact Form Example</h2>
<?php if(isset($success) && $success): ?>
<div class="success">
<h3>✅ Form Submitted Successfully!</h3>
<p>Thank you for your message, <strong><?php echo $name; ?></strong>!</p>
<p>We'll get back to you at <strong><?php echo $email; ?></strong>.</p>
</div>
<?php endif; ?>
<?php if(!empty($errors)): ?>
<div class="error">
<h3>❌ Please fix the following errors:</h3>
<ul>
<?php foreach($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="">
<div class="form-group">
<label for="name">Full Name:*</label>
<input type="text" id="name" name="name" required
value="<?php echo htmlspecialchars($name ?? ''); ?>">
</div>
<div class="form-group">
<label for="email">Email Address:*</label>
<input type="email" id="email" name="email" required
value="<?php echo htmlspecialchars($email ?? ''); ?>">
</div>
<div class="form-group">
<label for="age">Age:*</label>
<input type="number" id="age" name="age" min="1" max="120" required
value="<?php echo $age ?? ''; ?>">
</div>
<div class="form-group">
<label for="message">Message:*</label>
<textarea id="message" name="message" rows="5" required>
<?php echo htmlspecialchars($message ?? ''); ?>
</textarea>
</div>
<button type="submit">Send Message</button>
<button type="reset" style="background: #6c757d;">Clear Form</button>
</form>
<?php if(isset($success) && $success): ?>
<div style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 5px;">
<h4>Submitted Data:</h4>
<pre><?php
print_r([
'name' => $name,
'email' => $email,
'age' => $age,
'message' => $message
]);
?></pre>
</div>
<?php endif; ?>
</div>
</body>
</html>
06. 🍪 Sessions & Cookies
Sessions and cookies are used to maintain state across multiple page requests in web applications. They allow you to remember user information between different pages.
Sessions vs Cookies
Sessions:
• Store data on server
• More secure
• Temporary (expire when browser closes)
• No size limits
• Use $_SESSION superglobal
Cookies:
• Store data on client browser
• Less secure
• Can be persistent
• Limited size (~4KB)
• Use $_COOKIE superglobal
Common Uses
- User authentication and login systems
- Shopping carts in e-commerce
- User preferences and settings
- Tracking user activity
- Remembering login information
Example: Session & Cookie Management
<?php
// Start session at the beginning
session_start();
// Initialize session data
if (!isset($_SESSION['visit_count'])) {
$_SESSION['visit_count'] = 1;
$_SESSION['first_visit'] = date('Y-m-d H:i:s');
} else {
$_SESSION['visit_count']++;
}
// Set last visit time
$_SESSION['last_visit'] = date('Y-m-d H:i:s');
// Cookie management
$cookie_name = "user_preference";
$cookie_value = "dark_mode";
// Set cookie (expires in 30 days)
if (!isset($_COOKIE[$cookie_name])) {
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
}
// Handle login
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Simple authentication (in real app, use database with password_hash())
if ($username === "admin" && $password === "password123") {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$_SESSION['login_time'] = time();
// Regenerate session ID for security
session_regenerate_id(true);
// Set remember me cookie
if (isset($_POST['remember'])) {
setcookie("remember_user", $username, time() + (86400 * 30), "/");
}
header("Location: " . $_SERVER['PHP_SELF']);
exit();
} else {
$login_error = "Invalid username or password";
}
}
// Handle logout
if (isset($_GET['logout'])) {
// Clear session data
$_SESSION = array();
// Destroy session cookie
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-3600, '/');
}
// Destroy remember me cookie
setcookie("remember_user", "", time()-3600, "/");
// Destroy session
session_destroy();
header("Location: " . $_SERVER['PHP_SELF']);
exit();
}
// Check if user is remembered
if (isset($_COOKIE['remember_user']) && !isset($_SESSION['loggedin'])) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $_COOKIE['remember_user'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session & Cookie Demo</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; max-width: 800px; margin: 0 auto; }
.info-box { background: #e7f3ff; padding: 20px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #3498db; }
.login-box { background: #f8f9fa; padding: 20px; border-radius: 8px; border: 1px solid #ddd; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type="text"], input[type="password"] { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
button { background: #3498db; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #2980b9; }
.error { color: #e74c3c; margin-bottom: 15px; }
.success { color: #27ae60; margin-bottom: 15px; }
</style>
</head>
<body>
<h1>Session & Cookie Management Demo</h1>
<div class="info-box">
<h3>Session Information</h3>
<?php if(isset($_SESSION['loggedin']) && $_SESSION['loggedin']): ?>
<p class="success">✅ Welcome back, <strong><?php echo $_SESSION['username']; ?></strong>!</p>
<p>Login time: <?php echo date('H:i:s', $_SESSION['login_time']); ?></p>
<a href="?logout=true"><button>Logout</button></a>
<?php else: ?>
<p>You are not logged in</p>
<?php endif; ?>
<p>Visit count: <strong><?php echo $_SESSION['visit_count']; ?></strong></p>
<p>First visit: <?php echo $_SESSION['first_visit']; ?></p>
<p>Last visit: <?php echo $_SESSION['last_visit']; ?></p>
<p>Session ID: <code><?php echo session_id(); ?></code></p>
</div>
<div class="info-box">
<h3>Cookie Information</h3>
<p>Theme preference: <strong>
<?php echo isset($_COOKIE[$cookie_name]) ? $_COOKIE[$cookie_name] : 'Not set'; ?>
</strong></p>
<p>Remembered user: <strong>
<?php echo isset($_COOKIE['remember_user']) ? $_COOKIE['remember_user'] : 'None'; ?>
</strong></p>
<p>All cookies:</p>
<pre><?php print_r($_COOKIE); ?></pre>
</div>
<?php if(!isset($_SESSION['loggedin']) || !$_SESSION['loggedin']): ?>
<div class="login-box">
<h3>Login Form</h3>
<?php if(isset($login_error)): ?>
<p class="error">❌ <?php echo $login_error; ?></p>
<?php endif; ?>
<form method="POST" action="">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required
value="<?php echo isset($_COOKIE['remember_user']) ? $_COOKIE['remember_user'] : ''; ?>">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<div class="form-group">
<label>
<input type="checkbox" name="remember">
Remember me for 30 days
</label>
</div>
<button type="submit" name="login">Login</button>
</form>
<p style="margin-top: 15px; font-size: 0.9em; color: #666;">
Use: <strong>admin</strong> / <strong>password123</strong> to login
</p>
</div>
<?php endif; ?>
<div style="margin-top: 30px; padding: 15px; background: #f8f9fa; border-radius: 5px;">
<h4>All Session Data:</h4>
<pre><?php print_r($_SESSION); ?></pre>
</div>
</body>
</html>
07. 🗄️ MySQL Database
MySQL is the most popular database system used with PHP. PHP offers two main extensions for connecting to MySQL databases: MySQLi and PDO.
MySQLi vs PDO
MySQLi:
• Only works with MySQL databases
• Both procedural and object-oriented interfaces
• Good performance for MySQL-specific features
PDO (PHP Data Objects):
• Works with multiple database systems
• Only object-oriented interface
• Better for projects that might switch databases
Database Security Essentials
- Always use prepared statements to prevent SQL injection
- Validate and sanitize user input before database operations
- Use password_hash() for storing passwords
- Implement proper error handling
- Use parameterized queries
- Close database connections when done
Example: MySQL Database Operations
<?php
// Database configuration
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'test_db';
$port = 3306;
// ============================================
// MySQLi Example
// ============================================
echo "<h3>MySQLi Example</h3>";
// Create connection
$conn = mysqli_connect($host, $user, $password, $database, $port);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "✅ Connected to MySQL database<br>";
// Create users table
$sql = "CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "✅ Users table created/verified<br>";
} else {
echo "❌ Error creating table: " . mysqli_error($conn) . "<br>";
}
// Insert user with prepared statement
$username = "john_doe";
$email = "john@example.com";
$password_hash = password_hash("secure123", PASSWORD_DEFAULT);
$stmt = mysqli_prepare($conn,
"INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $password_hash);
if (mysqli_stmt_execute($stmt)) {
echo "✅ User inserted successfully<br>";
$last_id = mysqli_insert_id($conn);
echo "📝 Last inserted ID: $last_id<br>";
} else {
echo "❌ Error inserting user: " . mysqli_error($conn) . "<br>";
}
// Select users
$sql = "SELECT id, username, email, created_at FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<h4>Users in database:</h4>";
echo "<table border='1' cellpadding='8' style='border-collapse: collapse;'>";
echo "<tr><th>ID</th><th>Username</th><th>Email</th><th>Created At</th></tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . htmlspecialchars($row['username']) . "</td>";
echo "<td>" . htmlspecialchars($row['email']) . "</td>";
echo "<td>" . $row['created_at'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No users found<br>";
}
// Close MySQLi connection
mysqli_close($conn);
// ============================================
// PDO Example
// ============================================
echo "<hr><h3>PDO Example</h3>";
try {
// PDO Connection
$dsn = "mysql:host=$host;dbname=$database;port=$port;charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $password, $options);
echo "✅ PDO Connected successfully<br>";
// Create products table
$pdo->exec("CREATE TABLE IF NOT EXISTS products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
stock INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
echo "✅ Products table created/verified<br>";
// Insert products using transaction
$pdo->beginTransaction();
try {
$stmt = $pdo->prepare("INSERT INTO products (name, price, stock) VALUES (?, ?, ?)");
$products = [
['Laptop', 999.99, 10],
['Mouse', 25.50, 50],
['Keyboard', 75.00, 30],
['Monitor', 299.99, 15]
];
foreach ($products as $product) {
$stmt->execute($product);
}
$pdo->commit();
echo "✅ Products inserted successfully<br>";
} catch (Exception $e) {
$pdo->rollBack();
echo "❌ Transaction failed: " . $e->getMessage() . "<br>";
}
// Select products with WHERE clause
$stmt = $pdo->prepare("SELECT * FROM products WHERE price > ? ORDER BY price DESC");
$min_price = 50;
$stmt->execute([$min_price]);
$products = $stmt->fetchAll();
if (count($products) > 0) {
echo "<h4>Products (price > $min_price):</h4>";
echo "<table border='1' cellpadding='8' style='border-collapse: collapse;'>";
echo "<tr><th>ID</th><th>Name</th><th>Price</th><th>Stock</th></tr>";
foreach ($products as $product) {
echo "<tr>";
echo "<td>" . $product['id'] . "</td>";
echo "<td>" . htmlspecialchars($product['name']) . "</td>";
echo "<td>$" . number_format($product['price'], 2) . "</td>";
echo "<td>" . $product['stock'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
// Search with LIKE
$search_term = "%lap%";
$stmt = $pdo->prepare("SELECT * FROM products WHERE name LIKE ?");
$stmt->execute([$search_term]);
$search_results = $stmt->fetchAll();
if (count($search_results) > 0) {
echo "<h4>Search results for '$search_term':</h4>";
foreach ($search_results as $result) {
echo htmlspecialchars($result['name']) . " - $" . $result['price'] . "<br>";
}
}
// Aggregate functions
$stmt = $pdo->query("SELECT
COUNT(*) as total_products,
AVG(price) as avg_price,
SUM(stock) as total_stock,
MAX(price) as max_price,
MIN(price) as min_price
FROM products");
$stats = $stmt->fetch();
echo "<h4>Product Statistics:</h4>";
echo "Total Products: " . $stats['total_products'] . "<br>";
echo "Average Price: $" . number_format($stats['avg_price'], 2) . "<br>";
echo "Total Stock: " . $stats['total_stock'] . "<br>";
echo "Max Price: $" . number_format($stats['max_price'], 2) . "<br>";
echo "Min Price: $" . number_format($stats['min_price'], 2) . "<br>";
// Close PDO connection
$pdo = null;
} catch(PDOException $e) {
echo "❌ PDO Connection failed: " . $e->getMessage() . "<br>";
}
?>
08. 🏗️ OOP Basics
Object-Oriented Programming (OOP) organizes code around objects rather than functions. PHP provides comprehensive OOP support with classes, objects, inheritance, and polymorphism.
OOP Concepts
Class: Blueprint/template for objects
Object: Instance of a class
Properties: Variables within a class (data)
Methods: Functions within a class (behavior)
Constructor: Special method called when object is created
Destructor: Special method called when object is destroyed
Access Modifiers
- public: Accessible from anywhere
- protected: Accessible within the class and child classes
- private: Accessible only within the class
Example: Basic OOP Implementation
<?php
// Basic Class Definition
class Person {
// Properties (attributes)
private $name;
private $age;
private $email;
// Constructor - called when object is created
public function __construct($name, $age, $email) {
$this->name = $name;
$this->age = $age;
$this->email = $email;
echo "Person object created: $name<br>";
}
// Destructor - called when object is destroyed
public function __destruct() {
echo "Person object destroyed: {$this->name}<br>";
}
// Getter methods
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
public function getEmail() {
return $this->email;
}
// Setter methods
public function setName($name) {
$this->name = $name;
}
public function setAge($age) {
if ($age > 0 && $age < 150) {
$this->age = $age;
return true;
}
return false;
}
public function setEmail($email) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->email = $email;
return true;
}
return false;
}
// Display method
public function displayInfo() {
echo "<div style='border:1px solid #ddd; padding:10px; margin:10px;'>";
echo "<h3>Person Information</h3>";
echo "<p><strong>Name:</strong> {$this->name}</p>";
echo "<p><strong>Age:</strong> {$this->age}</p>";
echo "<p><strong>Email:</strong> {$this->email}</p>";
echo "</div>";
}
}
// Create Person objects
echo "<h3>Creating Person Objects</h3>";
$person1 = new Person("John Doe", 30, "john@example.com");
$person2 = new Person("Jane Smith", 25, "jane@example.com");
// Using getter methods
echo "<h4>Using Getter Methods</h4>";
echo "Person 1 Name: " . $person1->getName() . "<br>";
echo "Person 2 Age: " . $person2->getAge() . "<br>";
// Using setter methods
echo "<h4>Using Setter Methods</h4>";
$person1->setName("John Updated");
$person1->setAge(31);
echo "Updated Person 1: " . $person1->getName() . ", Age: " . $person1->getAge() . "<br>";
// Display information
$person1->displayInfo();
$person2->displayInfo();
// ============================================
// Inheritance Example
// ============================================
class Student extends Person {
private $studentId;
private $course;
private $grades = [];
public function __construct($name, $age, $email, $studentId, $course) {
parent::__construct($name, $age, $email);
$this->studentId = $studentId;
$this->course = $course;
}
public function getStudentId() {
return $this->studentId;
}
public function getCourse() {
return $this->course;
}
public function addGrade($subject, $grade) {
$this->grades[$subject] = $grade;
}
public function getGrades() {
return $this->grades;
}
public function getAverageGrade() {
if (empty($this->grades)) {
return 0;
}
return array_sum($this->grades) / count($this->grades);
}
// Method overriding
public function displayInfo() {
parent::displayInfo();
echo "<p><strong>Student ID:</strong> {$this->studentId}</p>";
echo "<p><strong>Course:</strong> {$this->course}</p>";
if (!empty($this->grades)) {
echo "<p><strong>Grades:</strong></p>";
echo "<ul>";
foreach ($this->grades as $subject => $grade) {
echo "<li>$subject: $grade</li>";
}
echo "</ul>";
echo "<p><strong>Average:</strong> " . number_format($this->getAverageGrade(), 2) . "</p>";
}
}
}
echo "<hr><h3>Inheritance Example</h3>";
$student1 = new Student("Alice Johnson", 22, "alice@example.com", "S12345", "Computer Science");
$student1->addGrade("Mathematics", 85);
$student1->addGrade("Programming", 92);
$student1->addGrade("Database", 88);
$student1->displayInfo();
// ============================================
// Static Methods and Properties
// ============================================
class MathHelper {
public static $pi = 3.14159;
public static function add($a, $b) {
return $a + $b;
}
public static function subtract($a, $b) {
return $a - $b;
}
public static function multiply($a, $b) {
return $a * $b;
}
public static function divide($a, $b) {
if ($b == 0) {
throw new Exception("Division by zero");
}
return $a / $b;
}
public static function circleArea($radius) {
return self::$pi * $radius * $radius;
}
}
echo "<hr><h3>Static Methods and Properties</h3>";
echo "5 + 3 = " . MathHelper::add(5, 3) . "<br>";
echo "10 - 4 = " . MathHelper::subtract(10, 4) . "<br>";
echo "Circle area (radius 5) = " . MathHelper::circleArea(5) . "<br>";
// ============================================
// Magic Methods
// ============================================
class MagicDemo {
private $data = [];
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
public function __toString() {
return "MagicDemo object with data: " . print_r($this->data, true);
}
}
echo "<hr><h3>Magic Methods</h3>";
$magic = new MagicDemo();
$magic->name = "Test";
$magic->value = 100;
echo $magic . "<br>";
echo "Name: " . $magic->name . "<br>";
?>
09. 🚀 Advanced OOP
Advanced OOP features in PHP include interfaces, abstract classes, traits, namespaces, and type declarations. These features help create more modular, maintainable, and scalable code.
Advanced OOP Concepts
Interfaces: Define method signatures without implementation
Abstract Classes: Cannot be instantiated, can contain implementation
Traits: Enable code reuse in single inheritance languages
Namespaces: Prevent naming conflicts
Type Declarations: Specify expected data types (PHP 7+)
Anonymous Classes: One-time use classes
When to Use Each Feature
- Interfaces: When multiple classes need to implement same methods
- Abstract Classes: When you need base class with some implementation
- Traits: When you need to reuse code across different class hierarchies
- Namespaces: Always use in larger projects to avoid conflicts
Example: Advanced OOP Features
<?php
// ============================================
// INTERFACES
// ============================================
interface Authenticable {
public function login($username, $password);
public function logout();
public function isLoggedIn();
}
interface Loggable {
public function log($message);
}
// ============================================
// ABSTRACT CLASS
// ============================================
abstract class DatabaseModel {
protected $connection;
abstract public function save();
abstract public function delete();
public function __construct() {
// Simulate database connection
$this->connection = true;
}
public function isConnected() {
return $this->connection;
}
}
// ============================================
// TRAITS
// ============================================
trait Timestampable {
protected $createdAt;
protected $updatedAt;
public function setTimestamps() {
$now = date('Y-m-d H:i:s');
$this->createdAt = $now;
$this->updatedAt = $now;
}
public function updateTimestamp() {
$this->updatedAt = date('Y-m-d H:i:s');
}
public function getCreatedAt() {
return $this->createdAt;
}
public function getUpdatedAt() {
return $this->updatedAt;
}
}
trait SoftDeletes {
protected $deletedAt = null;
public function delete() {
$this->deletedAt = date('Y-m-d H:i:s');
return "Soft deleted at: " . $this->deletedAt;
}
public function restore() {
$this->deletedAt = null;
return "Restored";
}
public function isDeleted() {
return $this->deletedAt !== null;
}
}
// ============================================
// CLASS USING INTERFACES, ABSTRACT CLASS, AND TRAITS
// ============================================
class User extends DatabaseModel implements Authenticable, Loggable {
use Timestampable, SoftDeletes;
private $username;
private $passwordHash;
private $isLoggedIn = false;
public function __construct($username, $password) {
parent::__construct();
$this->username = $username;
$this->passwordHash = password_hash($password, PASSWORD_DEFAULT);
$this->setTimestamps();
}
// Interface methods
public function login($username, $password) {
if ($username === $this->username && password_verify($password, $this->passwordHash)) {
$this->isLoggedIn = true;
$this->log("User {$username} logged in");
return true;
}
$this->log("Failed login attempt for {$username}");
return false;
}
public function logout() {
$this->isLoggedIn = false;
$this->log("User {$this->username} logged out");
}
public function isLoggedIn() {
return $this->isLoggedIn;
}
// Interface method
public function log($message) {
$timestamp = date('Y-m-d H:i:s');
echo "[$timestamp] $message<br>";
}
// Abstract class methods
public function save() {
if ($this->isConnected()) {
$this->updateTimestamp();
$this->log("User '{$this->username}' saved to database");
return "User '{$this->username}' saved successfully";
}
return "Error: Not connected to database";
}
// Override delete method from SoftDeletes trait
public function delete() {
$result = parent::delete(); // Call trait method
$this->log("User '{$this->username}' soft deleted");
return $result;
}
// Additional methods
public function changePassword($oldPassword, $newPassword) {
if (password_verify($oldPassword, $this->passwordHash)) {
$this->passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);
$this->updateTimestamp();
$this->log("Password changed for user '{$this->username}'");
return true;
}
return false;
}
public function getUsername() {
return $this->username;
}
}
// ============================================
// NAMESPACES
// ============================================
namespace App\Models;
class Product {
private $name;
private $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getName() {
return $this->name;
}
public function getPrice() {
return $this->price;
}
}
// ============================================
// TYPE DECLARATIONS (PHP 7+)
// ============================================
declare(strict_types=1);
class Calculator {
public function add(int $a, int $b): int {
return $a + $b;
}
public function divide(float $a, float $b): float {
if ($b == 0) {
throw new InvalidArgumentException("Division by zero");
}
return $a / $b;
}
public function concat(string $a, string $b): string {
return $a . $b;
}
}
// ============================================
// ANONYMOUS CLASSES (PHP 7+)
// ============================================
$logger = new class {
public function log($message) {
echo "[Anonymous Class] $message<br>";
}
};
// ============================================
// DEMONSTRATION
// ============================================
echo "<h3>Advanced OOP Features Demonstration</h3>";
// Create and use User object
$user = new User("admin", "securepassword");
echo "<h4>User Operations</h4>";
// Login
if ($user->login("admin", "securepassword")) {
echo "✅ Login successful<br>";
} else {
echo "❌ Login failed<br>";
}
echo "Is logged in? " . ($user->isLoggedIn() ? 'Yes' : 'No') . "<br>";
// Save user
echo $user->save() . "<br>";
// Change password
if ($user->changePassword("securepassword", "newpassword123")) {
echo "✅ Password changed successfully<br>";
} else {
echo "❌ Password change failed<br>";
}
// Soft delete
echo $user->delete() . "<br>";
echo "Is deleted? " . ($user->isDeleted() ? 'Yes' : 'No') . "<br>";
// Restore
echo $user->restore() . "<br>";
echo "Is deleted after restore? " . ($user->isDeleted() ? 'Yes' : 'No') . "<br>";
// Logout
$user->logout();
// Calculator with type declarations
echo "<h4>Calculator with Type Declarations</h4>";
$calc = new Calculator();
echo "5 + 3 = " . $calc->add(5, 3) . "<br>";
echo "10.5 / 2.5 = " . $calc->divide(10.5, 2.5) . "<br>";
echo "Hello + World = " . $calc->concat("Hello", "World") . "<br>";
// Anonymous class
echo "<h4>Anonymous Class</h4>";
$logger->log("This is a test message");
// Namespace demonstration
echo "<h4>Namespace Demonstration</h4>";
$product = new App\Models\Product("Laptop", 999.99);
echo "Product: " . $product->getName() . ", Price: $" . $product->getPrice() . "<br>";
// ============================================
// POLYMORPHISM
// ============================================
interface Shape {
public function area();
public function perimeter();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area(): float {
return pi() * $this->radius * $this->radius;
}
public function perimeter(): float {
return 2 * pi() * $this->radius;
}
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function area(): float {
return $this->width * $this->height;
}
public function perimeter(): float {
return 2 * ($this->width + $this->height);
}
}
echo "<h4>Polymorphism Example</h4>";
$shapes = [
new Circle(5),
new Rectangle(4, 6),
new Circle(3)
];
foreach ($shapes as $shape) {
echo "Area: " . number_format($shape->area(), 2) .
", Perimeter: " . number_format($shape->perimeter(), 2) . "<br>";
}
?>
10. 🔒 Security & Best Practices
PHP security is crucial for protecting web applications from common vulnerabilities and attacks. Implementing security best practices should be a priority from the beginning of development.
Common Security Vulnerabilities
SQL Injection: Attackers inject malicious SQL code
XSS (Cross-Site Scripting): Injecting malicious scripts into web pages
CSRF (Cross-Site Request Forgery): Unauthorized actions performed by authenticated users
Session Hijacking: Stealing session IDs to impersonate users
File Upload Vulnerabilities: Uploading malicious files to the server
Information Disclosure: Revealing sensitive information in error messages
Essential Security Practices
- Always validate and sanitize user input
- Use HTTPS for all communications
- Hash passwords with
password_hash() - Keep PHP and extensions updated
- Implement proper error handling without information disclosure
- Use prepared statements for database operations
- Set secure session configurations
- Implement CSRF tokens for forms
- Use Content Security Policy headers
- Regular security audits and penetration testing
Example: Comprehensive Security Implementation
<?php
// ============================================
// SECURE SESSION CONFIGURATION
// ============================================
session_start([
'cookie_httponly' => true, // Prevent JavaScript access to cookies
'cookie_secure' => true, // Only send cookies over HTTPS
'cookie_samesite' => 'Strict', // Prevent CSRF attacks
'use_strict_mode' => true, // Enhanced session security
'use_only_cookies' => true, // Don't accept session IDs in URLs
'cookie_lifetime' => 0, // Session cookie expires when browser closes
]);
// Regenerate session ID periodically
if (!isset($_SESSION['last_regeneration'])) {
session_regenerate_id(true);
$_SESSION['last_regeneration'] = time();
} elseif (time() - $_SESSION['last_regeneration'] > 300) { // Every 5 minutes
session_regenerate_id(true);
$_SESSION['last_regeneration'] = time();
}
// ============================================
// INPUT VALIDATION AND SANITIZATION
// ============================================
class InputValidator {
public static function sanitizeString($input) {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
return $input;
}
public static function validateEmail($email) {
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : false;
}
public static function validateURL($url) {
// Remove dangerous protocols
$dangerousProtocols = ['javascript:', 'data:', 'vbscript:'];
foreach ($dangerousProtocols as $protocol) {
if (stripos($url, $protocol) === 0) {
return false;
}
}
$url = filter_var($url, FILTER_SANITIZE_URL);
if (!filter_var($url, FILTER_VALIDATE_URL)) {
return false;
}
// Only allow http/https protocols
$parsed = parse_url($url);
if (!isset($parsed['scheme']) || !in_array(strtolower($parsed['scheme']), ['http', 'https'])) {
return false;
}
return $url;
}
public static function validateInteger($number, $min = null, $max = null) {
if (!is_numeric($number)) {
return false;
}
$number = (int)$number;
if ($min !== null && $number < $min) {
return false;
}
if ($max !== null && $number > $max) {
return false;
}
return $number;
}
public static function sanitizeHTML($html, $allowedTags = '<b><i><u><em><strong><code><pre>') {
$html = trim($html);
$html = strip_tags($html, $allowedTags);
$html = htmlspecialchars($html, ENT_QUOTES | ENT_HTML5, 'UTF-8');
return $html;
}
}
// ============================================
// PASSWORD SECURITY
// ============================================
class PasswordSecurity {
public static function hash($password) {
return password_hash($password, PASSWORD_DEFAULT);
}
public static function verify($password, $hash) {
return password_verify($password, $hash);
}
public static function needsRehash($hash) {
return password_needs_rehash($hash, PASSWORD_DEFAULT);
}
public static function generateStrongPassword($length = 12) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?';
$password = '';
$charsLength = strlen($chars) - 1;
for ($i = 0; $i < $length; $i++) {
$password .= $chars[random_int(0, $charsLength)];
}
return $password;
}
public static function checkStrength($password) {
$score = 0;
// Length check
if (strlen($password) >= 8) $score++;
if (strlen($password) >= 12) $score++;
// Character variety
if (preg_match('/[a-z]/', $password)) $score++;
if (preg_match('/[A-Z]/', $password)) $score++;
if (preg_match('/[0-9]/', $password)) $score++;
if (preg_match('/[^A-Za-z0-9]/', $password)) $score++;
return [
'score' => $score,
'strength' => $score >= 6 ? 'Strong' : ($score >= 4 ? 'Medium' : 'Weak')
];
}
}
// ============================================
// CSRF PROTECTION
// ============================================
class CSRFProtection {
private static $tokenName = 'csrf_token';
public static function generateToken() {
if (!isset($_SESSION[self::$tokenName])) {
$_SESSION[self::$tokenName] = bin2hex(random_bytes(32));
}
return $_SESSION[self::$tokenName];
}
public static function validateToken($token) {
if (!isset($_SESSION[self::$tokenName])) {
throw new Exception('CSRF token not found in session');
}
// Use hash_equals for timing attack prevention
if (!hash_equals($_SESSION[self::$tokenName], $token)) {
throw new Exception('CSRF token validation failed');
}
return true;
}
public static function getTokenField() {
$token = self::generateToken();
return "<input type='hidden' name='" . self::$tokenName . "' value='$token'>";
}
}
// ============================================
// SECURE DATABASE OPERATIONS
// ============================================
class SecureDatabase {
private $pdo;
public function __construct($host, $dbname, $username, $password) {
try {
$this->pdo = new PDO(
"mysql:host=$host;dbname=$dbname;charset=utf8mb4",
$username,
$password,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
]
);
} catch (PDOException $e) {
// Log error but don't expose details to user
error_log("Database connection failed: " . $e->getMessage());
throw new Exception("Could not connect to database. Please try again later.");
}
}
public function getUserByUsername($username) {
$stmt = $this->pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch();
}
public function createUser($username, $email, $password) {
$hash = PasswordSecurity::hash($password);
$stmt = $this->pdo->prepare(
"INSERT INTO users (username, email, password_hash, created_at)
VALUES (:username, :email, :hash, NOW())"
);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':hash', $hash, PDO::PARAM_STR);
return $stmt->execute();
}
public function searchUsers($searchTerm, $limit = 10, $offset = 0) {
$searchTerm = "%" . $searchTerm . "%";
$stmt = $this->pdo->prepare(
"SELECT id, username, email, created_at
FROM users
WHERE username LIKE :term OR email LIKE :term
LIMIT :limit OFFSET :offset"
);
$stmt->bindParam(':term', $searchTerm, PDO::PARAM_STR);
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
}
// ============================================
// SECURITY HEADERS
// ============================================
class SecurityHeaders {
public static function setHeaders() {
// Prevent clickjacking
header('X-Frame-Options: DENY');
// Enable XSS protection
header('X-XSS-Protection: 1; mode=block');
// Prevent MIME type sniffing
header('X-Content-Type-Options: nosniff');
// Referrer policy
header('Referrer-Policy: strict-origin-when-cross-origin');
// Content Security Policy (CSP)
self::setCSP();
// HSTS (should be configured in server, not PHP)
// header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}
private static function setCSP() {
$csp = [
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"font-src 'self'",
"connect-src 'self'",
"frame-ancestors 'none'",
"form-action 'self'",
"base-uri 'self'"
];
header("Content-Security-Policy: " . implode('; ', $csp));
}
}
// ============================================
// RATE LIMITING
// ============================================
class RateLimiter {
private $maxAttempts;
private $timeWindow;
public function __construct($maxAttempts = 5, $timeWindow = 300) {
$this->maxAttempts = $maxAttempts;
$this->timeWindow = $timeWindow;
}
public function check($identifier) {
$key = "rate_limit_$identifier";
$now = time();
if (!isset($_SESSION[$key])) {
$_SESSION[$key] = [
'attempts' => 1,
'first_attempt' => $now,
'last_attempt' => $now
];
return true;
}
$data = $_SESSION[$key];
// Reset if time window has passed
if ($now - $data['first_attempt'] > $this->timeWindow) {
$_SESSION[$key] = [
'attempts' => 1,
'first_attempt' => $now,
'last_attempt' => $now
];
return true;
}
// Check if exceeded max attempts
if ($data['attempts'] >= $this->maxAttempts) {
$waitTime = $this->timeWindow - ($now - $data['first_attempt']);
return [
'allowed' => false,
'wait_time' => $waitTime,
'message' => "Rate limit exceeded. Please wait $waitTime seconds."
];
}
// Increment attempts
$data['attempts']++;
$data['last_attempt'] = $now;
$_SESSION[$key] = $data;
return true;
}
public function getRemainingAttempts($identifier) {
$key = "rate_limit_$identifier";
if (!isset($_SESSION[$key])) {
return $this->maxAttempts;
}
$data = $_SESSION[$key];
$remaining = $this->maxAttempts - $data['attempts'];
return max(0, $remaining);
}
}
// ============================================
// DEMONSTRATION
// ============================================
echo "<h2>PHP Security Best Practices</h2>";
// Set security headers
SecurityHeaders::setHeaders();
// Generate CSRF token
$csrfToken = CSRFProtection::generateToken();
echo "<h3>CSRF Protection</h3>";
echo "CSRF Token Generated: " . substr($csrfToken, 0, 10) . "...<br>";
echo "CSRF Form Field: " . CSRFProtection::getTokenField() . "<br>";
// Password security demonstration
echo "<h3>Password Security</h3>";
$password = "MySecurePassword123!";
$hash = PasswordSecurity::hash($password);
echo "Password: $password<br>";
echo "Hash: " . substr($hash, 0, 20) . "...<br>";
echo "Verification: " . (PasswordSecurity::verify($password, $hash) ? '✅ Valid' : '❌ Invalid') . "<br>";
$strength = PasswordSecurity::checkStrength($password);
echo "Password Strength: {$strength['strength']} (Score: {$strength['score']}/6)<br>";
echo "Strong Password Example: " . PasswordSecurity::generateStrongPassword() . "<br>";
// Input validation demonstration
echo "<h3>Input Validation</h3>";
$testInput = "<script>alert('xss')</script>John O'Connor";
echo "Original: $testInput<br>";
echo "Sanitized: " . InputValidator::sanitizeString($testInput) . "<br>";
$email = "test@example.com<script>";
echo "Email Validation: " . (InputValidator::validateEmail($email) ? '✅ Valid' : '❌ Invalid') . "<br>";
// Rate limiting demonstration
echo "<h3>Rate Limiting</h3>";
$limiter = new RateLimiter(3, 60); // 3 attempts per minute
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$result = $limiter->check($ip);
if ($result === true) {
echo "✅ Request allowed. Remaining attempts: " . $limiter->getRemainingAttempts($ip) . "<br>";
} else {
echo "❌ " . $result['message'] . "<br>";
}
// Security checklist
echo "<h3>Security Checklist</h3>";
echo "<ul>";
echo "<li>✅ Input validation and sanitization</li>";
echo "<li>✅ Password hashing with password_hash()</li>";
echo "<li>✅ CSRF protection implemented</li>";
echo "<li>✅ SQL injection prevention with prepared statements</li>";
echo "<li>✅ Secure session configuration</li>";
echo "<li>✅ Security headers set</li>";
echo "<li>✅ Rate limiting implemented</li>";
echo "<li>✅ Error handling without information disclosure</li>";
echo "</ul>";
echo "<div class='key-concept' style='background: #d4edda; color: #155724; padding: 15px; margin: 20px 0;'>";
echo "<strong>Security Reminder:</strong> Always validate input, escape output, use HTTPS, keep software updated, and never trust user data. Security is an ongoing process, not a one-time setup.";
echo "</div>";
?>
Important: This security example demonstrates best practices. In production, always use HTTPS, keep PHP and all dependencies updated, conduct regular security audits, and monitor your application logs for suspicious activity.
Codcups
PHP Programming Course