PHP Examples
Learn by doing. Every example below can be opened in our online editor — change the code, press Run and see the result instantly.
Open the Try it Now editor »PHP Introduction
PHP Basics · 1 example<!DOCTYPE html>
<html>
<body>
<h1><?php echo 'Hello from PHP!'; ?></h1>
<p>Today is <?php echo date('l, d F Y'); ?>.</p>
</body>
</html>
Output in the browser: a heading "Hello from PHP!" and today's date, e.g. "Today is Tuesday, 01 December 2026." View the page source — you will see only HTML, no PHP.
PHP Installation
PHP Basics · 1 example<?php
// Save as test.php in htdocs and open http://localhost/test.php
echo 'PHP is working!<br>';
echo 'PHP version: ' . phpversion() . '<br>';
echo 'Server software: ' . $_SERVER['SERVER_SOFTWARE'];
Output: PHP is working! / PHP version: 8.3.x / Server software: Apache/2.4.x (your exact versions may differ).
PHP Syntax and Comments
PHP Basics · 1 example<?php
$student = 'Asha';
$marks = 86; // out of 100
/*
Decide the result
*/
$result = $marks >= 33 ? 'Pass' : 'Fail';
?>
<!DOCTYPE html>
<html>
<body>
<h2>Result card</h2>
<p>Name: <?= $student ?></p>
<p>Marks: <?= $marks ?></p>
<p>Result: <strong><?= $result ?></strong></p>
</body>
</html>
Output: Result card / Name: Asha / Marks: 86 / Result: Pass
PHP Variables
PHP Basics · 1 example<?php
$name = 'Ravi';
$city = 'Gaya';
$fee = 4999;
echo "Student: $name from $city<br>";
echo 'Single quotes: $name<br>';
echo 'Joined with dot: ' . $name . ' pays ₹' . $fee . '<br>';
$fee = $fee - 500; // change the value
echo "Fee after discount: ₹$fee";
Output: Student: Ravi from Gaya / Single quotes: $name / Joined with dot: Ravi pays ₹4999 / Fee after discount: ₹4499
PHP echo and print
PHP Basics · 1 example<?php
$course = 'PHP';
$lessons = 36;
$price = 2499.5;
$skills = ['Variables', 'Arrays', 'MySQL'];
echo "<h3>$course Course</h3>";
printf('%s has %d lessons and costs ₹%.2f<br>', $course, $lessons, $price);
echo '<pre>';
print_r($skills);
var_dump($price, true);
echo '</pre>';
Output: a heading "PHP Course", then "PHP has 36 lessons and costs ₹2499.50", then Array ( [0] => Variables [1] => Arrays [2] => MySQL ), then float(2499.5) and bool(true).
PHP Data Types
PHP Basics · 1 example<?php
$values = ['Asha', 21, 75.5, true, null, [1, 2]];
foreach ($values as $v) {
echo gettype($v) . '<br>';
}
$age = '25'; // from a form: string
var_dump($age); // string(2) "25"
$age = (int) $age;
var_dump($age); // int(25)
var_dump(is_numeric('12.5'), is_numeric('abc'));
Output: string, integer, double, boolean, NULL, array — then string(2) "25", int(25), bool(true), bool(false). (gettype returns "double" for floats.)
PHP Strings
Strings and Numbers · 1 example<?php
$first = 'Neha';
$last = 'Singh';
$full = $first . ' ' . $last;
$msg = "Welcome, $full!";
$msg .= ' Your course starts on Monday.';
$title = 'Certificate';
$card = <<<HTML
<div style="border:1px solid #ccc;padding:10px">
<h3>$title</h3>
<p>Awarded to $full</p>
</div>
HTML;
echo $msg . '<br>';
echo "Price: \$99<br>";
echo $card;
Output: Welcome, Neha Singh! Your course starts on Monday. / Price: $99 / a bordered box with "Certificate" and "Awarded to Neha Singh".
PHP String Functions
Strings and Numbers · 1 example<?php
$input = ' learn PHP string functions ';
$clean = trim($input);
echo ucwords($clean) . '<br>';
echo 'Length: ' . strlen($clean) . '<br>';
echo 'Has "PHP": ' . (str_contains($clean, 'PHP') ? 'yes' : 'no') . '<br>';
$slug = strtolower(str_replace(' ', '-', $clean));
echo "Slug: $slug<br>";
$tags = explode(',', 'php,mysql,laravel');
echo 'Tags: ' . implode(' | ', $tags) . '<br>';
echo 'Roll no: ' . str_pad('42', 5, '0', STR_PAD_LEFT);
Output: Learn PHP String Functions / Length: 26 / Has "PHP": yes / Slug: learn-php-string-functions / Tags: php | mysql | laravel / Roll no: 00042
PHP Numbers and Math
Strings and Numbers · 1 example<?php
$items = ['Notebook' => 60, 'Pen' => 15, 'Bag' => 899];
$subtotal = array_sum($items);
$gst = round($subtotal * 0.18, 2);
$total = $subtotal + $gst;
echo 'Subtotal: ₹' . number_format($subtotal, 2) . '<br>';
echo 'GST 18%: ₹' . number_format($gst, 2) . '<br>';
echo 'Total: ₹' . number_format($total, 2) . '<br>';
echo 'Rounded up: ₹' . ceil($total) . '<br>';
echo 'Lucky draw number: ' . random_int(1, 100) . '<br>';
echo 'EMI for 3 months: ₹' . round($total / 3, 2);
Output: Subtotal: ₹974.00 / GST 18%: ₹175.32 / Total: ₹1,149.32 / Rounded up: ₹1150 / Lucky draw number: (random) / EMI for 3 months: ₹383.11
PHP Constants
Strings and Numbers · 1 example<?php
define('SITE_NAME', 'AgyanAdda');
const GST_RATE = 18;
const SUPPORT_EMAIL = 'support@example.com';
function priceWithGst(float $price): float
{
return $price + $price * GST_RATE / 100;
}
echo 'Welcome to ' . SITE_NAME . '<br>';
echo 'Course price: ₹' . priceWithGst(1000) . '<br>';
echo 'Contact: ' . SUPPORT_EMAIL . '<br>';
echo 'This file is in: ' . __DIR__ . '<br>';
echo 'PHP version: ' . PHP_VERSION;
Output: Welcome to AgyanAdda / Course price: ₹1180 / Contact: support@example.com / the folder path / the PHP version.
PHP Operators
Operators and Control Flow · 1 example<?php
$a = 17;
$b = 5;
echo "$a + $b = " . ($a + $b) . '<br>';
echo "$a % $b = " . ($a % $b) . '<br>';
echo "2 ** 8 = " . (2 ** 8) . '<br>';
var_dump('5' == 5, '5' === 5);
echo '<br>';
$age = 19;
$hasId = true;
echo ($age >= 18 && $hasId) ? 'Can vote<br>' : 'Cannot vote<br>';
$city = $_GET['city'] ?? 'Gaya';
echo "City: $city<br>";
echo 'Compare 3 <=> 7: ' . (3 <=> 7);
Output: 17 + 5 = 22 / 17 % 5 = 2 / 2 ** 8 = 256 / bool(true) bool(false) / Can vote / City: Gaya (or the value in ?city=) / Compare 3 <=> 7: -1
PHP if else
Operators and Control Flow · 1 example<?php
$students = ['Asha' => 91, 'Ravi' => 68, 'Aman' => 29, 'Neha' => 77];
foreach ($students as $name => $marks) {
if ($marks >= 75) {
$grade = 'Distinction';
} elseif ($marks >= 60) {
$grade = 'First Division';
} elseif ($marks >= 33) {
$grade = 'Pass';
} else {
$grade = 'Fail';
}
$scholarship = ($marks >= 90) ? ' – Scholarship!' : '';
echo "$name ($marks): $grade$scholarship<br>";
}
?>
<?php $loggedIn = true; ?>
<?php if ($loggedIn): ?>
<p>Welcome back! <a href="#">Logout</a></p>
<?php else: ?>
<p><a href="#">Login</a></p>
<?php endif; ?>
Output: Asha (91): Distinction – Scholarship! / Ravi (68): First Division / Aman (29): Fail / Neha (77): Distinction / Welcome back! Logout
PHP switch and match
Operators and Control Flow · 1 example<?php
$status = 'shipped';
$label = match ($status) {
'pending' => '⏳ Waiting for payment',
'paid', 'processing' => '📦 Being packed',
'shipped' => '🚚 On the way',
'delivered' => '✅ Delivered',
default => 'Unknown status',
};
echo "Order: $label<br>";
$marks = 64;
$grade = match (true) {
$marks >= 75 => 'A',
$marks >= 60 => 'B',
$marks >= 33 => 'C',
default => 'F',
};
echo "Grade: $grade<br>";
$month = 2;
switch ($month) {
case 12:
case 1:
case 2:
echo 'Season: Winter';
break;
case 3:
case 4:
case 5:
echo 'Season: Summer';
break;
default:
echo 'Season: Monsoon or Autumn';
}
Output: Order: 🚚 On the way / Grade: B / Season: Winter
PHP Loops
Operators and Control Flow · 1 example<?php
$n = 9;
echo "<h4>Table of $n</h4>";
for ($i = 1; $i <= 10; $i++) {
echo "$n × $i = " . ($n * $i) . '<br>';
}
$marks = ['Hindi' => 78, 'English' => 25, 'Maths' => 92, 'Science' => 30];
echo '<h4>Passed subjects</h4><ul>';
foreach ($marks as $subject => $mark) {
if ($mark < 33) {
continue;
}
echo "<li>$subject: $mark</li>";
}
echo '</ul>';
$amount = 1000;
$years = 0;
while ($amount < 2000) {
$amount *= 1.08;
$years++;
}
echo "Money doubles in $years years at 8% interest.";
Output: the 9 times table, a list with Hindi: 78 and Maths: 92, and "Money doubles in 10 years at 8% interest."
PHP Functions
Functions · 1 example<?php
declare(strict_types=1);
function calculateFee(float $fee, float $discount = 0, bool $addGst = true): float
{
$amount = $fee - ($fee * $discount / 100);
if ($addGst) {
$amount += $amount * 0.18;
}
return round($amount, 2);
}
function formatRupees(float $amount): string
{
return '₹' . number_format($amount, 2);
}
echo formatRupees(calculateFee(5000)) . '<br>';
echo formatRupees(calculateFee(5000, 10)) . '<br>';
echo formatRupees(calculateFee(fee: 5000, addGst: false)) . '<br>';
$double = fn($n) => $n * 2;
echo 'Double of 21: ' . $double(21);
Output: ₹5,900.00 / ₹5,310.00 / ₹5,000.00 / Double of 21: 42
PHP Variable Scope
Functions · 1 example<?php
$siteName = 'AgyanAdda';
function welcome(string $site): string
{
$message = "Welcome to $site"; // local variable
return $message;
}
echo welcome($siteName) . '<br>';
function visitCounter(): int
{
static $visits = 0;
return ++$visits;
}
visitCounter();
visitCounter();
echo 'Visits: ' . visitCounter() . '<br>';
function addGrace(array &$marks, int $grace): void
{
foreach ($marks as &$m) {
$m = min(100, $m + $grace);
}
}
$marks = [30, 55, 98];
addGrace($marks, 5);
echo 'After grace: ' . implode(', ', $marks) . '<br>';
$rate = 18;
$withGst = fn($price) => $price + $price * $rate / 100; // arrow fn sees $rate
echo 'With GST: ' . $withGst(100);
Output: Welcome to AgyanAdda / Visits: 3 / After grace: 35, 60, 100 / With GST: 118
PHP Arrays
PHP Arrays · 1 example<?php
$courses = ['HTML', 'CSS', 'JavaScript'];
$courses[] = 'PHP';
array_unshift($courses, 'Computer Basics');
echo 'Total courses: ' . count($courses) . '<br>';
echo 'First: ' . $courses[0] . ', Last: ' . end($courses) . '<br>';
if (in_array('PHP', $courses)) {
echo 'PHP is available!<br>';
}
echo '<ol>';
foreach ($courses as $course) {
echo '<li>' . htmlspecialchars($course) . '</li>';
}
echo '</ol>';
$removed = array_pop($courses);
echo "Removed: $removed";
Output: Total courses: 5 / First: Computer Basics, Last: PHP / PHP is available! / a numbered list of 5 courses / Removed: PHP
PHP Associative Arrays
PHP Arrays · 1 example<?php
$student = [
'name' => 'Neha Kumari',
'roll' => 'BCA-2026-017',
'city' => 'Patna',
];
$marks = ['Maths' => 88, 'Computer' => 95, 'English' => 72];
$student['phone'] = '98xxxxxx10';
echo '<h4>' . $student['name'] . '</h4>';
echo 'Email: ' . ($student['email'] ?? 'Not provided') . '<br>';
echo '<table border="1" cellpadding="5">';
foreach ($marks as $subject => $mark) {
echo "<tr><td>$subject</td><td>$mark</td></tr>";
}
echo '</table>';
echo 'Total: ' . array_sum($marks) . '<br>';
echo 'Best subject: ' . array_search(max($marks), $marks) . '<br>';
echo 'Subjects: ' . implode(', ', array_keys($marks));
Output: Neha Kumari / Email: Not provided / a marks table / Total: 255 / Best subject: Computer / Subjects: Maths, Computer, English
PHP Multidimensional Arrays
PHP Arrays · 1 example<?php
$students = [
['name' => 'Asha', 'course' => 'BCA', 'fee' => 25000, 'paid' => true],
['name' => 'Ravi', 'course' => 'MCA', 'fee' => 40000, 'paid' => false],
['name' => 'Neha', 'course' => 'BCA', 'fee' => 25000, 'paid' => true],
['name' => 'Aman', 'course' => 'BSc', 'fee' => 18000, 'paid' => false],
];
usort($students, fn($a, $b) => $b['fee'] <=> $a['fee']);
echo '<table border="1" cellpadding="6"><tr><th>Name</th><th>Course</th><th>Fee</th><th>Status</th></tr>';
foreach ($students as $s) {
$status = $s['paid'] ? '✅ Paid' : '❌ Due';
echo "<tr><td>{$s['name']}</td><td>{$s['course']}</td><td>₹" . number_format($s['fee']) . "</td><td>$status</td></tr>";
}
echo '</table>';
$due = array_filter($students, fn($s) => !$s['paid']);
echo 'Total fees: ₹' . number_format(array_sum(array_column($students, 'fee'))) . '<br>';
echo 'Pending from: ' . implode(', ', array_column($due, 'name'));
Output: a table sorted by fee (Ravi first), then Total fees: ₹108,000 and Pending from: Ravi, Aman.
PHP Array Functions
PHP Arrays · 1 example<?php
$prices = ['Mouse' => 349, 'Keyboard' => 899, 'Monitor' => 7499, 'Pen Drive' => 499, 'Cable' => 149];
$withGst = array_map(fn($p) => round($p * 1.18), $prices);
$cheap = array_filter($prices, fn($p) => $p < 500);
$total = array_reduce($prices, fn($sum, $p) => $sum + $p, 0);
arsort($prices); // costliest first, keys kept
echo 'Costliest first: ' . implode(', ', array_keys($prices)) . '<br>';
echo 'Under ₹500: ' . implode(', ', array_keys($cheap)) . '<br>';
echo 'Mouse with GST: ₹' . $withGst['Mouse'] . '<br>';
echo 'Total: ₹' . number_format($total) . '<br>';
$frontend = ['HTML', 'CSS', 'JS'];
$backend = ['PHP', 'MySQL', 'PHP'];
$all = array_unique([...$frontend, ...$backend]);
echo 'Skills: ' . implode(', ', $all) . '<br>';
echo 'Pages: ' . json_encode(array_chunk($all, 2));
Output: Costliest first: Monitor, Keyboard, Pen Drive, Mouse, Cable / Under ₹500: Mouse, Pen Drive, Cable / Mouse with GST: ₹412 / Total: ₹9,395 / Skills: HTML, CSS, JS, PHP, MySQL / Pages: grouped in pairs.
PHP Superglobals
PHP Forms and Web · 1 example<?php
// Open as: superglobals.php?course=php&page=2
$course = $_GET['course'] ?? 'html';
$page = (int) ($_GET['page'] ?? 1);
echo 'Course: ' . htmlspecialchars($course) . '<br>';
echo "Page: $page<br>";
echo 'Method: ' . $_SERVER['REQUEST_METHOD'] . '<br>';
echo 'URL: ' . htmlspecialchars($_SERVER['REQUEST_URI']) . '<br>';
echo 'Your IP: ' . $_SERVER['REMOTE_ADDR'] . '<br>';
?>
<a href="?course=css&page=3">Open CSS, page 3</a>
Output: Course: php / Page: 2 / Method: GET / URL: /superglobals.php?course=php&page=2 / Your IP: 127.0.0.1 (on localhost). Clicking the link changes the values.
PHP Form Handling
PHP Forms and Web · 1 example<?php
$name = '';
$skills = [];
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
$course = $_POST['course'] ?? '';
$skills = $_POST['skills'] ?? [];
$message = 'Thank you, ' . htmlspecialchars($name) . '! You chose ' . htmlspecialchars($course)
. ' and know: ' . htmlspecialchars(implode(', ', $skills) ?: 'nothing yet') . '.';
}
?>
<form method="post">
<p><input name="name" placeholder="Your name" value="<?= htmlspecialchars($name) ?>"></p>
<p>
<select name="course">
<option>Web Development</option>
<option>PHP and Laravel</option>
</select>
</p>
<p>
<label><input type="checkbox" name="skills[]" value="HTML" <?= in_array('HTML', $skills) ? 'checked' : '' ?>> HTML</label>
<label><input type="checkbox" name="skills[]" value="CSS" <?= in_array('CSS', $skills) ? 'checked' : '' ?>> CSS</label>
</p>
<button>Send enquiry</button>
</form>
<p><?= $message ?></p>
After submitting, the page shows: Thank you, Asha! You chose PHP and Laravel and know: HTML, CSS. The name and checkboxes keep their values.
PHP Form Validation
PHP Forms and Web · 1 example<?php
$errors = [];
$old = ['name' => '', 'email' => '', 'mobile' => ''];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
foreach ($old as $field => $v) {
$old[$field] = trim($_POST[$field] ?? '');
}
if (mb_strlen($old['name']) < 3) {
$errors['name'] = 'Name must have at least 3 letters.';
}
if (!filter_var($old['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Enter a valid email address.';
}
if (!preg_match('/^[6-9]\d{9}$/', $old['mobile'])) {
$errors['mobile'] = 'Enter a valid 10-digit mobile number.';
}
if (!$errors) {
echo '<p style="color:green">Registered: ' . htmlspecialchars($old['name']) . '</p>';
$old = ['name' => '', 'email' => '', 'mobile' => ''];
}
}
function field(string $name, string $label, array $old, array $errors): string
{
$value = htmlspecialchars($old[$name]);
$error = isset($errors[$name]) ? '<br><small style="color:red">' . $errors[$name] . '</small>' : '';
return "<p>$label<br><input name=\"$name\" value=\"$value\">$error</p>";
}
?>
<form method="post" novalidate>
<?= field('name', 'Name', $old, $errors) ?>
<?= field('email', 'Email', $old, $errors) ?>
<?= field('mobile', 'Mobile', $old, $errors) ?>
<button>Register</button>
</form>
Submitting empty or wrong values shows a red message under each field and keeps what the user typed. Correct values show "Registered: Name".
PHP include and require
PHP Forms and Web · 1 example<?php
// ---- config.php ----
return [
'site_name' => 'AgyanAdda',
'phone' => '+91 98xxxxxx10',
];
// ---- partials/header.php ----
// <header><h2><?= $config['site_name'] ?></h2><nav>Home | Tutorials | Contact</nav></header>
// ---- partials/footer.php ----
// <footer>Call us: <?= $config['phone'] ?> · © <?= date('Y') ?></footer>
// ---- about.php ----
$config = require __DIR__ . '/config.php';
$pageTitle = 'About us';
require __DIR__ . '/partials/header.php';
echo "<h1>$pageTitle</h1><p>We teach coding in simple language.</p>";
require __DIR__ . '/partials/footer.php';
This example spans four files. about.php shows the shared header, its own content and the shared footer. Change the phone number in config.php and every page updates.
PHP Sessions
PHP Forms and Web · 1 example<?php
session_start();
// Demo user (in real apps, read from the database and use password_verify)
$demoEmail = 'student@example.com';
$demoHash = password_hash('secret123', PASSWORD_DEFAULT);
if (isset($_GET['logout'])) {
$_SESSION = [];
session_destroy();
header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($_POST['email'] === $demoEmail && password_verify($_POST['password'], $demoHash)) {
session_regenerate_id(true);
$_SESSION['user'] = 'Asha';
$_SESSION['flash'] = 'Login successful!';
} else {
$_SESSION['flash'] = 'Wrong email or password.';
}
}
if (!empty($_SESSION['flash'])) {
echo '<p><strong>' . $_SESSION['flash'] . '</strong></p>';
unset($_SESSION['flash']);
}
if (isset($_SESSION['user'])): ?>
<h3>Welcome, <?= htmlspecialchars($_SESSION['user']) ?>!</h3>
<a href="?logout=1">Logout</a>
<?php else: ?>
<form method="post">
<input name="email" placeholder="student@example.com">
<input name="password" type="password" placeholder="secret123">
<button>Login</button>
</form>
<?php endif; ?>
Log in with student@example.com / secret123. Reload the page — you stay logged in because the session remembers you. Click Logout to end the session.
PHP Cookies
PHP Forms and Web · 1 example<?php
$allowed = ['en' => 'English', 'hi' => 'हिन्दी'];
if (isset($_GET['lang']) && isset($allowed[$_GET['lang']])) {
setcookie('lang', $_GET['lang'], [
'expires' => time() + 60 * 60 * 24 * 365,
'path' => '/',
'httponly' => true,
'samesite' => 'Lax',
]);
$_COOKIE['lang'] = $_GET['lang']; // use it on this request too
}
if (isset($_GET['forget'])) {
setcookie('lang', '', time() - 3600, '/');
unset($_COOKIE['lang']);
}
$lang = $_COOKIE['lang'] ?? 'en';
$greeting = $lang === 'hi' ? 'नमस्ते! आपका स्वागत है।' : 'Hello! Welcome.';
?>
<h3><?= $greeting ?></h3>
<p>Language: <?= $allowed[$lang] ?></p>
<a href="?lang=en">English</a> | <a href="?lang=hi">हिन्दी</a> | <a href="?forget=1">Forget</a>
Choose a language, close and reopen the page — the cookie remembers your choice for a year.
PHP File Upload
PHP Forms and Web · 1 example<?php
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['photo'])) {
$file = $_FILES['photo'];
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
$maxBytes = 2 * 1024 * 1024; // 2 MB
if ($file['error'] !== UPLOAD_ERR_OK) {
$message = 'Upload failed. Please choose a file.';
} elseif ($file['size'] > $maxBytes) {
$message = 'File is larger than 2 MB.';
} else {
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
if (!isset($allowed[$mime])) {
$message = 'Only JPG, PNG or WEBP images are allowed.';
} else {
$dir = __DIR__ . '/uploads';
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$newName = bin2hex(random_bytes(8)) . '.' . $allowed[$mime];
if (move_uploaded_file($file['tmp_name'], "$dir/$newName")) {
$message = "Uploaded! <br><img src=\"uploads/$newName\" width=\"150\">";
}
}
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="photo" accept="image/*">
<button>Upload photo</button>
</form>
<p><?= $message ?></p>
Upload a JPG/PNG under 2 MB to see it displayed. A renamed .php or .exe file is rejected because finfo checks the real file type.
PHP Date and Time
PHP Forms and Web · 1 example<?php
date_default_timezone_set('Asia/Kolkata');
echo 'Today: ' . date('l, d F Y') . '<br>';
echo 'Time: ' . date('h:i A') . '<br>';
echo 'Indian format: ' . date('d-m-Y') . '<br>';
echo 'Fee due date: ' . date('d M Y', strtotime('+15 days')) . '<br>';
$today = new DateTimeImmutable('today');
$exam = new DateTimeImmutable(date('Y') . '-12-31');
$days = $today->diff($exam)->days;
echo "Days left this year: $days<br>";
$dob = new DateTimeImmutable('2004-08-15');
echo 'Age: ' . $dob->diff($today)->y . ' years<br>';
$next = $today->modify('+1 month');
echo 'Next payment: ' . $next->format('d/m/Y');
Output (on 1 December 2026, morning): Today: Tuesday, 01 December 2026 / Time: 10:30 AM / Indian format: 01-12-2026 / Fee due date: 16 Dec 2026 / Days left this year: 30 / Age: 22 years / Next payment: 01/01/2027
PHP MySQL Connect
PHP and MySQL · 1 example<?php
// db.php
$config = [
'host' => '127.0.0.1',
'db' => 'school',
'user' => 'root',
'pass' => '',
];
try {
$pdo = new PDO(
"mysql:host={$config['host']};dbname={$config['db']};charset=utf8mb4",
$config['user'],
$config['pass'],
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
} catch (PDOException $e) {
error_log($e->getMessage()); // log the real error privately
exit('Database connection failed. Please try again later.');
}
// test.php
// require __DIR__ . '/db.php';
// echo 'Connected! MySQL version: ' . $pdo->query('SELECT VERSION()')->fetchColumn();
If the details are correct, test.php prints "Connected! MySQL version: 8.x". On failure, the visitor sees a friendly message while the real error goes to the log.
PHP MySQL CRUD
PHP and MySQL · 1 example<?php
require __DIR__ . '/db.php';
function e(?string $v): string { return htmlspecialchars((string) $v); }
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
if ($action === 'create' && trim($_POST['name']) !== '') {
$stmt = $pdo->prepare('INSERT INTO students (name, email, course) VALUES (:name, :email, :course)');
$stmt->execute([
'name' => trim($_POST['name']),
'email' => trim($_POST['email']) ?: null,
'course' => $_POST['course'],
]);
}
if ($action === 'update') {
$stmt = $pdo->prepare('UPDATE students SET course = ? WHERE id = ?');
$stmt->execute([$_POST['course'], (int) $_POST['id']]);
}
if ($action === 'delete') {
$stmt = $pdo->prepare('DELETE FROM students WHERE id = ?');
$stmt->execute([(int) $_POST['id']]);
}
header('Location: ' . $_SERVER['PHP_SELF']); // Post/Redirect/Get
exit;
}
$search = trim($_GET['q'] ?? '');
$stmt = $pdo->prepare('SELECT * FROM students WHERE name LIKE ? ORDER BY id DESC');
$stmt->execute(['%' . $search . '%']);
$students = $stmt->fetchAll();
?>
<form method="post">
<input type="hidden" name="action" value="create">
<input name="name" placeholder="Name" required>
<input name="email" type="email" placeholder="Email">
<select name="course"><option>BCA</option><option>MCA</option><option>BSc IT</option></select>
<button>Add</button>
</form>
<form><input name="q" value="<?= e($search) ?>" placeholder="Search name"> <button>Search</button></form>
<table border="1" cellpadding="6">
<tr><th>ID</th><th>Name</th><th>Email</th><th>Course</th><th>Actions</th></tr>
<?php foreach ($students as $s): ?>
<tr>
<td><?= $s['id'] ?></td>
<td><?= e($s['name']) ?></td>
<td><?= e($s['email']) ?></td>
<td>
<form method="post" style="display:inline">
<input type="hidden" name="action" value="update">
<input type="hidden" name="id" value="<?= $s['id'] ?>">
<select name="course" onchange="this.form.submit()">
<?php foreach (['BCA', 'MCA', 'BSc IT'] as $c): ?>
<option <?= $c === $s['course'] ? 'selected' : '' ?>><?= $c ?></option>
<?php endforeach; ?>
</select>
</form>
</td>
<td>
<form method="post" onsubmit="return confirm('Delete this student?')">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id" value="<?= $s['id'] ?>">
<button>Delete</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
Uses db.php and the students table from the previous lesson. You can add, search, change the course and delete students — every query uses prepared statements.
PHP OOP Classes and Objects
OOP and Advanced PHP · 1 example<?php
class BankAccount
{
public const MIN_BALANCE = 500;
private static int $count = 0;
public function __construct(
public readonly string $holder,
private float $balance = 0,
) {
self::$count++;
}
public function deposit(float $amount): static
{
$this->balance += $amount;
return $this;
}
public function withdraw(float $amount): static
{
if ($this->balance - $amount < self::MIN_BALANCE) {
throw new Exception('Minimum balance of ₹' . self::MIN_BALANCE . ' required.');
}
$this->balance -= $amount;
return $this;
}
public function balance(): string
{
return '₹' . number_format($this->balance, 2);
}
public static function total(): int
{
return self::$count;
}
}
$asha = new BankAccount('Asha', 1000);
$asha->deposit(2500)->withdraw(800);
echo "{$asha->holder}: {$asha->balance()}<br>";
$ravi = new BankAccount('Ravi');
try {
$ravi->withdraw(100);
} catch (Exception $e) {
echo 'Ravi: ' . $e->getMessage() . '<br>';
}
echo 'Accounts opened: ' . BankAccount::total();
Output: Asha: ₹2,700.00 / Ravi: Minimum balance of ₹500 required. / Accounts opened: 2
PHP Inheritance, Interfaces and Traits
OOP and Advanced PHP · 1 example<?php
interface Refundable
{
public function refund(float $amount): string;
}
trait LogsActivity
{
public function log(string $message): void
{
echo '[' . date('H:i') . '] ' . static::class . ": $message<br>";
}
}
abstract class Payment
{
use LogsActivity;
public function __construct(protected string $customer) {}
abstract public function pay(float $amount): string;
protected function rupees(float $amount): string
{
return '₹' . number_format($amount, 2);
}
}
class UpiPayment extends Payment implements Refundable
{
public function __construct(string $customer, private string $upiId)
{
parent::__construct($customer);
}
public function pay(float $amount): string
{
$this->log("paying {$this->rupees($amount)}");
return "{$this->customer} paid {$this->rupees($amount)} via UPI ({$this->upiId})";
}
public function refund(float $amount): string
{
return "Refunded {$this->rupees($amount)} to {$this->upiId}";
}
}
class CashPayment extends Payment
{
public function pay(float $amount): string
{
$this->log('cash received');
return "{$this->customer} paid {$this->rupees($amount)} in cash";
}
}
$payments = [new UpiPayment('Asha', 'asha@upi'), new CashPayment('Ravi')];
foreach ($payments as $p) {
echo $p->pay(1499) . '<br>';
if ($p instanceof Refundable) {
echo $p->refund(200) . '<br>';
}
}
Output: a log line and "Asha paid ₹1,499.00 via UPI (asha@upi)", "Refunded ₹200.00 to asha@upi", then a log line and "Ravi paid ₹1,499.00 in cash".
PHP Exceptions and Error Handling
OOP and Advanced PHP · 1 example<?php
class InsufficientBalanceException extends Exception
{
public function __construct(public readonly float $shortBy)
{
parent::__construct('Insufficient balance. Short by ₹' . number_format($shortBy, 2));
}
}
function payFromWallet(float $balance, float $amount): float
{
if ($amount <= 0) {
throw new InvalidArgumentException('Amount must be positive.');
}
if ($amount > $balance) {
throw new InsufficientBalanceException($amount - $balance);
}
return $balance - $amount;
}
$tests = [[1000, 300], [1000, 1500], [1000, -5]];
foreach ($tests as [$balance, $amount]) {
try {
$left = payFromWallet($balance, $amount);
echo "Paid ₹$amount. Balance left: ₹$left<br>";
} catch (InsufficientBalanceException $e) {
echo $e->getMessage() . ' – please add money.<br>';
} catch (InvalidArgumentException $e) {
echo 'Invalid input: ' . $e->getMessage() . '<br>';
} finally {
echo '<small>Transaction checked.</small><br>';
}
}
Output: Paid ₹300. Balance left: ₹700 / Insufficient balance. Short by ₹500.00 – please add money. / Invalid input: Amount must be positive. — each followed by "Transaction checked."
PHP JSON and APIs
OOP and Advanced PHP · 1 example<?php
// api.php → api.php?id=2
$courses = [
1 => ['id' => 1, 'title' => 'HTML', 'lessons' => 33, 'hindi' => 'एचटीएमएल'],
2 => ['id' => 2, 'title' => 'PHP', 'lessons' => 36, 'hindi' => 'पीएचपी'],
];
header('Content-Type: application/json; charset=utf-8');
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($id === null) {
echo json_encode(['data' => array_values($courses)], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} elseif ($id === false || !isset($courses[$id])) {
http_response_code(404);
echo json_encode(['error' => 'Course not found']);
} else {
echo json_encode(['data' => $courses[$id]], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
// ---- client.php: reading the API ----
// $json = file_get_contents('http://localhost/api.php?id=2');
// $course = json_decode($json, true);
// echo $course['data']['title']; // PHP
api.php?id=2 returns { "data": { "id": 2, "title": "PHP", "lessons": 36, "hindi": "पीएचपी" } }. A missing id returns status 404 with an error message.
PHP Namespaces and Composer
OOP and Advanced PHP · 1 example<?php
// ---- app/Services/FeeCalculator.php ----
namespace App\Services;
class FeeCalculator
{
public function __construct(private float $gstRate = 18) {}
public function total(float $fee): float
{
return round($fee * (1 + $this->gstRate / 100), 2);
}
}
// ---- app/Models/Course.php ----
// namespace App\Models;
// class Course { public function __construct(public string $title, public float $fee) {} }
// ---- index.php ----
// require __DIR__ . '/vendor/autoload.php';
//
// use App\Models\Course;
// use App\Services\FeeCalculator;
// use Carbon\Carbon; // installed with: composer require nesbot/carbon
//
// $course = new Course('PHP Masterclass', 4999);
// $calc = new FeeCalculator();
// echo $course->title . ': ₹' . $calc->total($course->fee) . '<br>';
// echo 'Batch starts ' . Carbon::now()->addWeek()->format('d M Y');
With composer.json autoload set to "App\\": "app/" and composer dump-autoload run, index.php prints: PHP Masterclass: ₹5898.82 / Batch starts (next week's date).
PHP Security Best Practices
OOP and Advanced PHP · 1 example<?php
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
function e(string $v): string
{
return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) {
http_response_code(419);
exit('Invalid or expired form. Please reload the page.');
}
$name = trim($_POST['name'] ?? '');
$password = $_POST['password'] ?? '';
if (mb_strlen($password) < 8) {
$message = 'Password must be at least 8 characters.';
} else {
$hash = password_hash($password, PASSWORD_DEFAULT);
// Save $name and $hash with a prepared statement here
$message = 'Account created for ' . e($name) . '.<br>Stored hash starts with: ' . e(substr($hash, 0, 20)) . '...';
$message .= '<br>Password check: ' . (password_verify($password, $hash) ? 'match ✓' : 'no match');
}
}
?>
<form method="post">
<input type="hidden" name="csrf" value="<?= e($_SESSION['csrf']) ?>">
<input name="name" placeholder="Name" required>
<input name="password" type="password" placeholder="Password (8+ characters)" required>
<button>Create account</button>
</form>
<p><?= $message ?></p>
The form includes a hidden CSRF token that must match the session. The password is stored only as a secure hash (it starts with $2y$), and password_verify() checks it at login.