PHP is an open-source, server-side scripting language embedded in HTML: the server runs the code and sends only the resulting HTML. Superglobals for forms, sessions and cookies, plus PDO/MySQLi prepared statements, make it the classic language for database-driven pages.
High-yield 70 minSyllabus: “Server side scripting: PHP”
Mark as
The idea in one minute
Imagine a printing press that prints a fresh newspaper for each reader. The page template is fixed, but wherever the editor wrote 'insert the reader's name here' or 'insert today's list of housing schemes', the press looks up the answer and prints it in. PHP is that press: the <?php … ?> markers are the editor's notes, the server fills them in, and the reader receives only the finished paper — never the notes.
Key points — the night-before list
PHP: Hypertext Preprocessor (originally Personal Home Page), created by Rasmus Lerdorf in 1994. Server-side, interpreted (Zend Engine), embedded in HTML with <?php … ?>; files end in .php.
Variables start with $, are case-sensitive and dynamically typed; . concatenates; == compares after type juggling, === also checks type; <=> returns −1/0/1; ?? supplies defaults.
Arrays: indexed, associative (key ⇒ value) and multidimensional. sort/rsort renumber keys; asort/arsort sort by value keeping keys; ksort/krsort sort by key.
Superglobals: $_GET, $_POST, $_REQUEST, $_SERVER, $_SESSION, $_COOKIE, $_FILES, $_ENV, $GLOBALS. Always escape output with htmlspecialchars() to stop XSS.
Sessions: session_start() → $_SESSION; cookie PHPSESSID; unset($_SESSION['x']) removes one value, session_unset() all values, session_destroy() the server-side data.
setcookie(name, value, expiry) must run before any output; delete with an expiry in the past (time() − 3600). Cookies set now appear in $_COOKIE only on the next request.
include → warning and continue if the file is missing; require → fatal error. The _once forms skip files already loaded.
Database: MySQLi (MySQL only) or PDO (many databases); prepared statements with bound parameters prevent SQL injection; store passwords with password_hash(), check with password_verify().
01What PHP is and how a PHP page runs
PHP is a general-purpose scripting language designed for the web. Rasmus Lerdorf wrote the first version in 1994 — a set of C programs called Personal Home Page Tools — and released it in 1995. Andi Gutmans and Zeev Suraski rewrote it as PHP 3 (1998) and renamed it PHP: Hypertext Preprocessor, a recursive acronym. PHP 4 (2000) introduced the Zend Engine, PHP 5 (2004) a full object model (and PDO in 5.1), PHP 7 (2015) a large speed-up, and PHP 8 (2020) a JIT compiler, named arguments and match.
PHP is server-side: the browser never receives PHP code. When a request for a .php file arrives, the web server hands it to the PHP engine (through mod_php in Apache or PHP-FPM with Nginx). The engine compiles the script to opcodes (OPcache keeps them for later requests), runs it, and everything the script prints — together with the plain HTML around the PHP blocks — becomes the response.
PHPThe browser receives only <p>Report generated on 03-12-2026</p> and <p>Open schemes: 4</p> — no PHP
<!DOCTYPE html>
<html>
<body>
<h1>Housing schemes</h1>
<?php
$today = date("d-m-Y"); // runs on the server
echo "<p>Report generated on $today</p>";
?>
<p>Open schemes: <?= 3 + 1 ?></p> <!-- short echo tag -->
</body>
</html>
<?php … ?> is the standard tag pair; <?= expr ?> is short for <?php echo expr; ?>. In a file that is pure PHP, leave out the closing ?> so stray whitespace cannot be sent.
Statements end with ;. Comments: // or # to end of line, /* … */ for blocks.
echo is a language construct with no return value that can print several comma-separated items (echo "a", "b";). print takes one argument and returns 1, so it can appear inside expressions. print_r() and var_dump() (which also shows types) are for debugging.
exit() or its alias die("message") stops the script immediately.
PSC favourite
PHP is not a client-side script (asked in 2026 — CSS, HTML and VBScript run in the browser; PHP runs on the server). Use die() to terminate script execution (asked in 2022).
02Variables, data types, constants and scope
PHP
<?php
$name = "Anil"; // string
$units = 120; // int
$rate = 7.5; // float
$open = true; // bool
$tags = ["EWS", "LIG"]; // array
$none = null; // null
var_dump($units); // int(120)
echo gettype($rate); // double — gettype's name for float
var_dump((int) "42abc"); // int(42): a cast reads the leading digits
var_dump("10" + 5); // int(15): numeric strings convert in arithmetic
$Name = "Someone else"; // variable names are case-sensitive: $name and $Name differ
ECHO $name; // keywords and function names are not: ECHO works
$field = "district";
$$field = "Kollam"; // a variable variable: this creates $district
echo $district; // Kollam
define("MAX_UNITS", 5000); // constant defined at run time (may sit inside an if)
const BOARD = "KSHB"; // compile-time constant, also allowed in classes
echo MAX_UNITS, " ", BOARD, " ", __LINE__; // constants have no $; __LINE__ is a magic constant
Variable names start with $ followed by a letter or underscore. Variables need no declaration and no type: the type belongs to the current value (dynamic, loose typing).
Types: scalar — bool, int, float, string; compound — array, object, callable, iterable; special — null and resource (an open file or connection).
Inspect with gettype(), var_dump(), is_int(), is_string(), is_numeric(); convert with casts (int), (string) or settype().
A reference makes two names share one value: after $y = &$x; any change through either name is seen through both.
PHPFunction scope: globals must be imported with global or $GLOBALS; static locals survive between calls
<?php
$count = 5; // global scope
function show() {
// echo $count; // Warning: undefined variable — functions do not see globals
global $count; // import it (or read $GLOBALS["count"])
echo $count; // 5
}
function visits() {
static $n = 0; // initialised once, keeps its value between calls
$n++;
return $n;
}
visits();
visits();
echo visits(); // 3
<?php
$name = "Anil";
$scheme = ["units" => 120];
echo 'Hello $name\n'; // Hello $name\n — single quotes: no interpolation; only \' and \\ are escapes
echo "Hello $name\n"; // Hello Anil and a newline — double quotes interpolate
echo "Units: {$scheme['units']}"; // braces for array elements and expressions
echo 'It\'s ' . $name . '!'; // . is the concatenation operator
$letter = <<<EOT
Dear $name,
your application has been received.
EOT;
// heredoc (above) behaves like a double-quoted string over several lines
$plain = <<<'EOT'
No $interpolation inside a nowdoc.
EOT;
Null coalescing: left side unless it is null or unset
$_GET["page"] ?? 1
?:
Ternary and short ternary
$n > 0 ? "yes" : "no" · $a ?: "default"
&& || ! and and or xor
Logical; the word forms bind more loosely than =
$x = true and false; leaves $x true
PHP 8 made loose comparison saner. A number compared with a non-numeric string is now compared as strings, so 0 == "abc" is false (it was true in PHP 7). Numeric strings still compare as numbers: "1" == "01", "10" == "1e1" and 100 == "1e2" are all true. Other classic loose results: null == false, [] == false and "" == null are true. Use === unless you want juggling.
04Control structures, arrays and functions
PHP
<?php
$units = 120;
$district = "Kollam";
if ($units > 100) {
echo "Large";
} elseif ($units > 50) { // also written else if
echo "Medium";
} else {
echo "Small";
}
switch ($district) { // loose comparison; falls through without break
case "Kollam":
case "Thiruvananthapuram":
$zone = "South";
break;
default:
$zone = "Other";
}
$size = match (true) { // PHP 8: strict, returns a value, no fall-through
$units > 100 => "Large",
$units > 50 => "Medium",
default => "Small",
};
for ($i = 1; $i <= 3; $i++) { echo $i; } // 123
$n = 3;
while ($n > 0) { echo $n--; } // 321
do { echo "once"; } while (false); // a do-while body runs at least once
$_GET and $_POST together (and $_COOKIE, depending on php.ini's request_order)
$_SERVER
Request and server details: REQUEST_METHOD, PHP_SELF, SERVER_NAME, HTTP_HOST, HTTP_USER_AGENT, REMOTE_ADDR, QUERY_STRING, REQUEST_URI, DOCUMENT_ROOT
$_SESSION
Session variables for this user (after session_start())
$_COOKIE
Cookies sent by the browser
$_FILES
Uploaded files: name, type, tmp_name, error, size
$_ENV
Environment variables
$GLOBALS
Every global variable, by name
PHPOne file shows the form, validates the POST, re-displays entered values ('sticky' fields) and lists errors
<?php
$errors = [];
$name = $email = $mobile = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$mobile = trim($_POST["mobile"] ?? "");
if (strlen($name) < 3) {
$errors[] = "Name must have at least 3 characters.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Enter a valid e-mail address.";
}
if (!preg_match('/^[6-9][0-9]{9}$/', $mobile)) {
$errors[] = "Mobile must be 10 digits starting with 6-9.";
}
if (!$errors) {
// save to the database (next sections), then redirect: Post/Redirect/Get
header("Location: thanks.php");
exit;
}
}
?>
<form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<input name="name" value="<?= htmlspecialchars($name) ?>">
<input name="email" value="<?= htmlspecialchars($email) ?>">
<input name="mobile" value="<?= htmlspecialchars($mobile) ?>">
<button>Register</button>
</form>
<?php foreach ($errors as $e): ?>
<p class="error"><?= htmlspecialchars($e) ?></p>
<?php endforeach; ?>
Check $_SERVER["REQUEST_METHOD"] to tell a first visit (GET) from a submission (POST).
$_POST["name"] ?? "" avoids warnings when a field is missing; isset() tests existence, empty() also treats "", "0", 0 and null as empty.
Validate on the server even if HTML5 or JavaScript validated in the browser: filter_var() with FILTER_VALIDATE_EMAIL / FILTER_VALIDATE_INT, preg_match() for patterns, ctype_digit().
Escape every value you print with htmlspecialchars(), which turns &<>"' into entities. Printed raw, a name like <script>…</script> would run in other users' browsers — cross-site scripting (XSS). Even $_SERVER['PHP_SELF'] must be escaped.
After a successful POST, redirect with header("Location: …") and exit so refreshing the page does not resubmit (Post/Redirect/Get). Headers must be sent before any output.
PSC favourite
A form with method="post" and a field named user is read with $_POST['user'] or $_REQUEST['user'] — both work (asked in 2025). $_GET['user'] would be empty.
06Cookies, sessions, uploads and include/require
PHP
<?php
// cookies travel in HTTP headers, so set them before ANY output
setcookie("district", "Kollam", time() + 30 * 24 * 3600, "/"); // lasts 30 days
setcookie("lang", "ml", [ // options form (PHP 7.3+)
"expires" => time() + 86400,
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Lax",
]);
setcookie("district", "", time() - 3600, "/"); // delete: same name and path, expiry in the past
echo $_COOKIE["district"] ?? "not set yet"; // output comes last; a new cookie appears in $_COOKIE only on the NEXT request
Session function
Effect
session_start()
Create a new session or resume the one named by the PHPSESSID cookie; call it before any output on every page that uses $_SESSION
$_SESSION["user"] = "anil";
Store a value (any serialisable type: strings, numbers, arrays)
unset($_SESSION["cart"]);
Remove one session variable
session_unset() or $_SESSION = [];
Remove all session variables (the session itself continues)
session_destroy()
Delete the session's data on the server; $_SESSION keeps its values until the script ends and the cookie stays until it expires
session_regenerate_id(true)
Issue a new session id and delete the old one — call it right after login
session_id(), session_name()
The current id and the cookie name (PHPSESSID by default)
By default the data lives in a file on the server — e.g. /var/lib/php/sessions/sess_9f2c1ab7e4d3 — and only the random id travels to the browser in the PHPSESSID cookie, which is a session cookie (it lasts until the browser closes). Unused sessions are garbage-collected after session.gc_maxlifetime, 1440 seconds (24 minutes) by default. Hardening settings in php.ini: session.cookie_httponly = 1, session.cookie_secure = 1, session.use_strict_mode = 1, session.use_only_cookies = 1.
PHPUpload limits come from php.ini: file_uploads, upload_max_filesize (2M by default) and post_max_size (8M)
<!-- the form needs: <form method="post" enctype="multipart/form-data"> and <input type="file" name="photo"> -->
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["photo"])) {
$f = $_FILES["photo"]; // name, type, tmp_name, error, size
if ($f["error"] !== UPLOAD_ERR_OK) {
die("Upload failed, error code " . $f["error"]);
}
if ($f["size"] > 2 * 1024 * 1024) {
die("File larger than 2 MB");
}
$type = mime_content_type($f["tmp_name"]); // inspect the real content, not the browser's claim
if (!in_array($type, ["image/jpeg", "image/png"], true)) {
die("Only JPEG or PNG images are allowed");
}
$safeName = bin2hex(random_bytes(8)) . ($type === "image/png" ? ".png" : ".jpg");
move_uploaded_file($f["tmp_name"], __DIR__ . "/uploads/" . $safeName);
echo "Saved as $safeName";
}
Statement
If the file is missing
Typical use
include "menu.php";
E_WARNING — the script carries on
Optional parts: sidebars, banners
require "db.php";
Fatal error — the script stops
Essentials: configuration, database connection, function libraries
include_once / require_once
As above, but a file already loaded is not loaded again
Files that define functions or classes (avoids 'Cannot redeclare')
07Databases: MySQLi, PDO and the login example
MySQLi (MySQL improved)
Works only with MySQL / MariaDB
Procedural (mysqli_query) and object-oriented styles
Positional ? placeholders with bind_param("si", …) type letters
Replaced the old mysql_* functions, which PHP 7 removed
PDO (PHP Data Objects)
One API for a dozen databases through drivers (MySQL, PostgreSQL, SQLite, SQL Server, Oracle…)
Object-oriented only
Positional ? or named :name placeholders
Exceptions on error with ERRMODE_EXCEPTION; easy transactions
SQL injection happens when user input is pasted into SQL text. If a login script builds "SELECT * FROM users WHERE username = '$u'" and someone types ' OR '1'='1' -- as the user name, the database receives SELECT * FROM users WHERE username = '' OR '1'='1' -- ' — a condition true for every row. A prepared statement sends the SQL with placeholders first and the values separately, so input can never change the query's structure.
PHPMySQLi with a prepared statement (since PHP 8.1 MySQLi throws mysqli_sql_exception on errors by default)
<?php
$conn = new mysqli("localhost", getenv("KSHB_DB_USER"), getenv("KSHB_DB_PASS"), "kshb");
$district = $_GET["district"] ?? "Kollam";
$min = 50;
$stmt = $conn->prepare("SELECT name, units FROM schemes WHERE district = ? AND units >= ?");
$stmt->bind_param("si", $district, $min); // s = string, i = integer (d = double, b = blob)
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) { // one associative array per row
echo htmlspecialchars($row["name"]), " – ", $row["units"], " units<br>";
}
$stmt->close();
$conn->close();
The running example of this module — a login form, a session, a 'Welcome, name' page and a list of records from the database — uses two tables. Passwords are never stored as plain text: a setup script stores password_hash("s3cret", PASSWORD_DEFAULT) (a salted bcrypt hash) and the login page checks it with password_verify().
SQLThe same two tables are used by the JSP and ASP.NET versions of the example
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL UNIQUE,
full_name VARCHAR(60) NOT NULL,
password_hash VARCHAR(255) NOT NULL -- output of password_hash(), never the password
);
CREATE TABLE schemes (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(80) NOT NULL,
district VARCHAR(40) NOT NULL,
units INT NOT NULL
);
INSERT INTO schemes (name, district, units) VALUES
('Sneha Nagar', 'Kollam', 120), ('Kayal View Flats', 'Alappuzha', 64), ('Thanal Homes', 'Thrissur', 48);
PHP
<?php
// db.php — one shared PDO connection; pages load it with require
$pdo = new PDO(
"mysql:host=localhost;dbname=kshb;charset=utf8mb4",
getenv("KSHB_DB_USER"),
getenv("KSHB_DB_PASS"),
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // errors throw PDOException
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // rows as associative arrays
]
);
PHP
<?php
// login.php — shows the form (GET) and checks the credentials (POST)
session_start();
require "db.php";
$error = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$username = trim($_POST["username"] ?? "");
$password = $_POST["password"] ?? "";
if ($username === "" || $password === "") {
$error = "Enter both username and password.";
} else {
$stmt = $pdo->prepare("SELECT id, full_name, password_hash FROM users WHERE username = ?");
$stmt->execute([$username]); // the value travels separately: no injection
$user = $stmt->fetch();
if ($user && password_verify($password, $user["password_hash"])) {
session_regenerate_id(true); // fresh id after login (stops session fixation)
$_SESSION["user_id"] = $user["id"];
$_SESSION["full_name"] = $user["full_name"];
header("Location: welcome.php"); // Post/Redirect/Get
exit;
}
$error = "Invalid username or password."; // same message for both cases: no hints
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Staff login</title></head>
<body>
<h1>Staff login</h1>
<?php if ($error !== ""): ?>
<p class="error"><?= htmlspecialchars($error) ?></p>
<?php endif; ?>
<form method="post" action="login.php">
<label for="u">Username</label>
<input id="u" name="username" required value="<?= htmlspecialchars($_POST["username"] ?? "") ?>">
<label for="p">Password</label>
<input id="p" name="password" type="password" required>
<button type="submit">Log in</button>
</form>
</body>
</html>
PHPquery() is safe here because no user input enters the SQL; any user-supplied value would need prepare()
<?php
// welcome.php — only for logged-in users
session_start();
if (!isset($_SESSION["user_id"])) { // no session data means not logged in
header("Location: login.php");
exit;
}
require "db.php";
$schemes = $pdo->query("SELECT name, district, units FROM schemes ORDER BY name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Welcome</title></head>
<body>
<h1>Welcome, <?= htmlspecialchars($_SESSION["full_name"]) ?></h1>
<table>
<tr><th>Scheme</th><th>District</th><th>Units</th></tr>
<?php foreach ($schemes as $s): ?>
<tr>
<td><?= htmlspecialchars($s["name"]) ?></td>
<td><?= htmlspecialchars($s["district"]) ?></td>
<td><?= (int) $s["units"] ?></td>
</tr>
<?php endforeach; ?>
</table>
<p><a href="logout.php">Log out</a></p>
</body>
</html>
PHP
<?php
// logout.php — end the session completely
session_start();
$_SESSION = []; // 1. forget the data in this request
$p = session_get_cookie_params();
setcookie(session_name(), "", time() - 3600,
$p["path"], $p["domain"], $p["secure"], $p["httponly"]); // 2. expire PHPSESSID
session_destroy(); // 3. delete the server-side session file
header("Location: login.php");
exit;
Other PDO essentials: named placeholders (INSERT INTO schemes (name, district, units) VALUES (:n, :d, :u) executed with [":n" => $n, ":d" => $d, ":u" => $u]), $pdo->lastInsertId(), $stmt->rowCount(), fetchAll(), fetchColumn(), and transactions with beginTransaction(), commit() and rollBack() inside try/catch. Try the HTTP, forms & sessions tool to watch this login turn into a POST, a Set-Cookie and server-side session state.
08Errors, exceptions, OOP — and PHP vs JSP vs ASP.NET
Classic PHP errors have levels — E_ERROR (fatal), E_WARNING, E_NOTICE, E_PARSE, E_DEPRECATED; error_reporting(E_ALL) reports them all. In production set display_errors = Off and log_errors = On so visitors never see file paths or SQL. Since PHP 7 most fatal problems are thrown as Error objects, so modern code uses exceptions: everything throwable implements Throwable, with the branches Error (TypeError, DivisionByZeroError, ArgumentCountError) and Exception (PDOException, InvalidArgumentException, RuntimeException…).
PHP
<?php
function allot(int $left, int $requested): int {
if ($requested <= 0) {
throw new InvalidArgumentException("Requested units must be positive");
}
if ($requested > $left) {
throw new RuntimeException("Only $left units left");
}
return $left - $requested;
}
try {
echo allot(5, 8);
} catch (InvalidArgumentException $e) {
echo "Bad input: ", $e->getMessage();
} catch (RuntimeException $e) {
echo "Cannot allot: ", $e->getMessage(); // Cannot allot: Only 5 units left
} finally {
echo " (checked)"; // always runs
}
PHPClasses, interfaces, abstract methods, visibility (public/protected/private), $this-> and :: for static members
<?php
interface Allottable {
public function allot(int $n): void;
}
abstract class Scheme implements Allottable {
public function __construct(
protected string $name, // constructor property promotion (PHP 8)
protected int $units
) {}
abstract public function category(): string;
public function allot(int $n): void {
if ($n > $this->units) {
throw new RuntimeException("Not enough units");
}
$this->units -= $n;
}
public function __toString(): string { // a magic method: used when the object is echoed
return "{$this->name} ({$this->category()}): {$this->units} units";
}
}
class RentalScheme extends Scheme { // single inheritance
public function category(): string { return "Rental"; }
}
$s = new RentalScheme("Sneha Nagar", 120);
$s->allot(20);
echo $s; // Sneha Nagar (Rental): 100 units
PHP classes support single inheritance (extends), multiple interfaces (implements), traits (use) for reusing method sets across unrelated classes, static members (self::, parent::, static::) and namespaces. Magic methods start with two underscores and are called by PHP itself: __construct, __destruct, __get, __set, __call, __toString, __invoke, __clone, __sleep, __wakeup.
Aspect
PHP
JSP / servlets
ASP.NET
Language
PHP
Java
C# (or VB.NET)
Origin
Rasmus Lerdorf, 1994–95
Sun: servlets 1997, JSP 1999
Microsoft, 2002
Execution
Compiled to opcodes by the Zend Engine (OPcache; JIT in PHP 8)
Page translated to a servlet, compiled to bytecode, run on the JVM
Compiled to MSIL and JIT-compiled by the CLR
Server
Apache (mod_php) or Nginx + PHP-FPM, any OS
Servlet container: Tomcat, Jetty, WildFly…
IIS on Windows (Web Forms); ASP.NET Core also on Linux (Kestrel)
Page files
.php
.jsp plus servlet classes
.aspx markup + .aspx.cs code-behind
Session API
$_SESSION["user"]
session.setAttribute("user", …)
Session["user"]
Database API
PDO, MySQLi
JDBC (PreparedStatement)
ADO.NET (SqlCommand), Entity Framework
Typical database
MySQL / MariaDB
Oracle, MySQL, PostgreSQL
SQL Server
Licence / cost
Free and open source
Free JDK and servers (commercial app servers exist)
Free .NET; Windows Server licence for IIS hosting
Strengths
Cheap hosting everywhere, gentle learning curve, CMSs like WordPress
Start each time from $u = ["Sneha" => 120, "Kayal" => 64, "Thanal" => 48, "Harbour" => 60]; and give the print_r() result after sort($u), asort($u), arsort($u), ksort($u) and krsort($u).
EX 3SQL injection — the attack and the fix
A login script runs $sql = "SELECT * FROM users WHERE username = '$u' AND password_hash = '$h'"; with $u taken straight from $_POST. An attacker types admin' -- as the user name. Show the query the database receives, explain the damage, and rewrite it safely.
EX 4unset vs session_unset vs session_destroy
A page runs session_start() and holds $_SESSION = ["user" => "anil", "cart" => [7, 12]]. Describe the state after each separate action: (a) unset($_SESSION["cart"]) (b) session_unset() (c) session_destroy() followed by echo $_SESSION["user"] in the same script (d) the next request after (c).
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Write PHP that reads district from the query string (default 'All') and safely prints 'Showing schemes in' followed by that district. What would happen with ?district=<script>alert(1)</script> if you forgot to escape?
Write a visit counter that remembers how many times a browser has opened the page, for one year, using a cookie. Why can't the new value be read from $_COOKIE in the same request in which it is set?
Q4
Rewrite this unsafe MySQLi code with PDO and named placeholders: $r = mysqli_query($c, "INSERT INTO schemes (name, district, units) VALUES ('$n', '$d', $u)"); Then print the new row's id.
Q5
This check never prints 'found' for the input 'KSHB portal'. Explain why and fix it: if (strpos($text, "KSHB")) { echo "found"; }
Exam traps
session_destroy() deletes the server-side data but does not empty $_SESSION for the rest of the script or delete the cookie; unset($_SESSION['x']) removes just one variable.
setcookie() and header() must run before any output — even a blank line before <?php causes 'headers already sent'.
strpos() can return 0 (found at the start), which is falsy — always test !== false.
sort() throws away keys; use asort() to keep the key ⇒ value association.
htmlspecialchars() prevents XSS; it does nothing against SQL injection — use prepared statements (or, second best, mysqli_real_escape_string()).
Magic methods use two underscores (__construct, __wakeup); some exam options print one.
Quiz — KPSC style
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.