optional · CSS study notes
19. Server-Side Programming using PHP
CSS Optional — Paper-II, Section-B · P-II.VI.19 · Expect "write a PHP script" (form handling, database, sessions) and "explain how PHP works".
1. Server-Side Programming
- Code that runs on the web server to generate dynamic responses: reads requests, applies business logic, accesses databases, manages sessions, returns HTML/JSON. The browser only receives the output, never the code.
- Languages: PHP, Java (Servlets/JSP), Python (Django/Flask), C# (ASP.NET), JavaScript (Node.js), Ruby (Rails).
2. PHP Overview
- PHP: Hypertext Preprocessor (a recursive acronym; originally "Personal Home Page"), created by Rasmus Lerdorf in 1994. Open-source, interpreted, loosely typed, embedded in HTML.
- Runs with Apache/Nginx (via PHP-FPM); classic LAMP stack (Linux, Apache, MySQL, PHP). Powers WordPress and a large share of websites whose server language is known.
- Frameworks: Laravel, Symfony, CodeIgniter, CakePHP.
3. How PHP Works
graph LR
B["Browser: GET /profile.php"] --> W["Web server (Apache/Nginx)"]
W --> P["PHP interpreter executes script"]
P <--> D[("MySQL database")]
P -->|"generated HTML"| W
W -->|"HTTP response (HTML only)"| B
4. Syntax Essentials
<?php
// Variables start with $; no type declaration
$name = "Awais";
$age = 28;
$gpa = 3.6;
$isAdmin = false;
echo "Hello, " . $name . "
"; // . concatenates strings
echo "Age: $age"; // double quotes interpolate variables
// Arrays
$cities = ["Karachi", "Lahore", "Quetta"]; // indexed
$marks = ["Math" => 85, "CS" => 92]; // associative
foreach ($marks as $subject => $score) {
echo "$subject: $score
";
}
// Control structures
if ($gpa >= 3.5) { echo "Dean's list"; }
elseif ($gpa >= 2.0) { echo "Pass"; }
else { echo "Probation"; }
for ($i = 1; $i <= 5; $i++) { echo $i * $i . " "; } // 1 4 9 16 25
// Functions
function grade($score) {
return $score >= 85 ? "A" : ($score >= 70 ? "B" : "C");
}
echo grade(92); // A
?>
Data types: string, integer, float, boolean, array, object, NULL, resource.
Superglobals: $_GET, $_POST, $_REQUEST, $_SESSION, $_COOKIE, $_SERVER, $_FILES, $_ENV, $GLOBALS.
5. Form Handling (GET/POST)
<!-- form.html -->
<form action="register.php" method="post">
Name: <input type="text" name="name">
Email: <input type="email" name="email">
<button type="submit">Submit</button>
</form>
<?php
// register.php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
if ($name === "" || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Please enter a valid name and email.";
} else {
echo "Welcome, " . htmlspecialchars($name); // escape output -> prevents XSS
}
}
?>
6. Database Access with PDO (secure)
<?php
$pdo = new PDO("mysql:host=localhost;dbname=school", "user", "secret",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
// INSERT with a prepared statement (prevents SQL injection)
$stmt = $pdo->prepare("INSERT INTO students (name, email) VALUES (?, ?)");
$stmt->execute([$name, $email]);
// SELECT
$stmt = $pdo->prepare("SELECT name, email FROM students WHERE program = ?");
$stmt->execute(["BSCS"]);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo htmlspecialchars($row["name"]) . " - " . htmlspecialchars($row["email"]) . "
";
}
?>
Never build SQL by concatenating user input ("... WHERE name = '$name'") — that enables SQL injection.
7. Sessions and Cookies (login example)
<?php
session_start(); // must come before any output
$stmt = $pdo->prepare("SELECT id, password_hash FROM users WHERE email = ?");
$stmt->execute([$_POST["email"]]);
$user = $stmt->fetch();
if ($user && password_verify($_POST["password"], $user["password_hash"])) {
session_regenerate_id(true); // prevent session fixation
$_SESSION["user_id"] = $user["id"];
setcookie("theme", "dark", time() + 86400 * 30, "/"); // 30-day cookie
header("Location: dashboard.php");
} else {
echo "Invalid credentials";
}
?>
| Point | Session | Cookie |
|---|---|---|
| Stored | On the server (only an ID in a cookie) | In the browser |
| Security | More secure | User can view/modify |
| Lifetime | Until logout/timeout/browser close | Until set expiry |
| Capacity | Large | About 4 KB |
8. Useful Distinctions
includevsrequire: on a missing file, include gives a warning and continues; require gives a fatal error and stops.include_once/require_onceavoid double inclusion.echovsprint: echo can output several values and returns nothing; print returns 1.==(loose, type juggling) vs===(strict).- Single quotes do not interpolate variables; double quotes do.
9. PHP Security Checklist
Prepared statements (SQL injection) · htmlspecialchars on output (XSS) · password_hash/password_verify (never MD5) · CSRF tokens on forms · validate/limit file uploads · session_regenerate_id after login · hide error details in production · HTTPS only.
📐 Output-Prediction Practice
<?php
$x = "5"; $y = 3;
echo $x + $y; // 8 (numeric string converted)
echo $x . $y; // 53 (concatenation)
var_dump("5" == 5); // bool(true)
var_dump("5" === 5); // bool(false)
$a = [3, 1, 2]; sort($a); echo implode(",", $a); // 1,2,3
echo strlen("Pakistan"); // 8
echo strtoupper("css"); // CSS
?>
🎯 CSS Exam Angle
Show the request flow diagram, then a complete form → PHP → database example using prepared statements. Mentioning htmlspecialchars, password_hash and prepared statements signals secure-coding awareness that examiners reward.
⚠️ MCQ Traps
- PHP variables start with $; string concatenation uses . (dot), not +.
- PHP code runs on the server; the browser never sees it.
requirestops on error;includecontinues.session_start()must be called before any output.- Single-quoted strings do not expand variables.
✅ Self-Check (with Answers)
Q1. Write PHP to print numbers 1 to 10 that are even.
Ans: <?php for ($i = 1; $i <= 10; $i++) { if ($i % 2 == 0) echo $i . " "; } ?> → 2 4 6 8 10
Q2. How do you read a field named "city" submitted by GET and by POST?
Ans: $_GET["city"] for GET and $_POST["city"] for POST ($_REQUEST["city"] reads either).
Q3. Why are prepared statements used?
Ans: They send the SQL structure and user data separately, so input is always treated as data, never as SQL code — preventing SQL injection; they can also be reused efficiently.
Q4. Differentiate sessions and cookies.
Ans: Session data is stored on the server with only an ID in a cookie — more secure and larger; cookies store data in the browser, are sent with each request, limited to about 4 KB and can be modified by the user.
Q5. Predict: $a = 10; $b = "10"; var_dump($a == $b, $a === $b);
Ans: bool(true) bool(false) — loose comparison converts types; strict also compares type (int vs string).
Q6. What does htmlspecialchars() protect against?
Ans: Cross-site scripting (XSS): it converts characters like < > & " into HTML entities, so user input is displayed as text instead of being executed as HTML/JavaScript.
📜 Past-Paper Questions & MCQs (CSS 2016–2026)
2022 · Paper-II · Q8(c) · 6 marks
Q. Explain how you can access a database from a JSP page. Give the database connectivity issues in detail.
Ans.
- Steps (JDBC in JSP):
- Step 1: Load the JDBC driver:
Class.forName("com.mysql.cj.jdbc.Driver"); - Step 2: Open a connection:
Connection con = DriverManager.getConnection(url, user, password); - Step 3: Create a
PreparedStatement(orStatement). - Step 4: Execute:
ResultSet rs = ps.executeQuery();(orexecuteUpdate()for INSERT, UPDATE, DELETE). - Step 5: Read the rows with
rs.next()andrs.getString("name"), and show them in the page. - Step 6: Close the
ResultSet, statement and connection in afinallyblock.
- Step 1: Load the JDBC driver:
<%@ page import="java.sql.*" %>
<%
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/shop", "user", "pass");
PreparedStatement ps = con.prepareStatement("SELECT name, price FROM product WHERE price > ?");
ps.setInt(1, 100);
ResultSet rs = ps.executeQuery();
while (rs.next()) { out.println(rs.getString("name") + " " + rs.getInt("price") + "
"); }
rs.close(); ps.close(); con.close();
%>
- Connectivity issues:
- the driver is missing or has the wrong version, or the URL and credentials are wrong
- connection leaks from not closing connections, and the cost of opening a connection for every request (solution: connection pooling)
- SQL injection (use prepared statements) and storing passwords in the page (use configuration or a data source)
- network failures and timeouts, and the database being down
- transaction handling and concurrency (commit, rollback, locking)
- mixing business logic and database code in the page (better to use servlets or DAO classes)
- character-encoding and data-type mismatches
MCQs
2024 P-II · Q18. Which of the following statement/s are true about PHP?
- (A) Echo and print are the same
- (B) Echo takes a single parameter
- (C) Both (A) and (B)
- (D) None of these ✅
- Answer: (D) None of these.
- Why:
echoandprintdiffer.echocan take several comma-separated arguments and returns nothing, whileprinttakes exactly one argument and returns 1. So (A) is false, and (B) is false because echo is not limited to a single parameter.
2024 P-II · Q20. PHP allows dynamic code execution using:
- (A)
eval()✅ - (B) Reflection API
- (C) File manipulation
- (D) None of these
- Answer: (A)
eval(). - Why:
eval()takes a string and runs it as PHP code at run time. The Reflection API only inspects classes and functions, and file functions read and write files (they run code only if the file is later included).