Web Programming IIUnit 89 min read
Advanced PHP: Security, OOP, and File Handling
Unit 8 of Web Programming II builds on PHP fundamentals to teach object-oriented programming (OOP), advanced file handling, and critical security concepts—including SQL injection prevention, session management, and secure authentication—with hands-on examples and real-world applications like e-commerce and user account
TAKEAWAYS
- Learn OOP principles (classes, objects, inheritance, polymorphism) to write modular, reusable PHP code.
- Master file handling (reading/writing files, directories, and sessions) for dynamic data storage.
- Understand security threats (SQL injection, XSS, CSRF) and how to defend against them with prepared statements and input validation.
- Implement sessions and cookies to manage user logins and persistent data securely.
- Compare array types (indexed, associative, multidimensional) and their use cases.
- Apply error handling (try-catch blocks) to debug PHP applications gracefully.
1. Object-Oriented Programming (OOP) in PHP
PHP 5+ fully supports OOP, enabling cleaner, scalable code. Key concepts:
1.1 Classes and Objects
A class is a blueprint; an object is an instance of that class.
classDiagram
class Person {
+String name
+int age
+void greet()
}
Person --> Person: "Object of Person class"Example: Define a Book class
<?php
class Book {
public $title;
public $author;
public function __construct($title, $author) {
$this->title = $title;
$this->author = $author;
}
public function displayInfo() {
echo "Title: {$this->title}, Author: {$this->author}";
}
}
// Create an object
$book = new Book("PHP for Beginners", "John Doe");
$book->displayInfo();
Output:
Title: PHP for Beginners, Author: John Doe
1.2 Inheritance
A child class inherits properties/methods from a parent class.
classDiagram
class Animal {
+void eat()
}
class Dog {
+void bark()
+void eat()
}
Animal <|-- DogExample: Extend Book to EBook
class EBook extends Book {
public $fileSize;
public function __construct($title, $author, $fileSize) {
parent::__construct($title, $author);
$this->fileSize = $fileSize;
}
public function displayInfo() {
parent::displayInfo();
echo ", File Size: {$this->fileSize} MB";
}
}
$ebook = new EBook("Advanced PHP", "Jane Smith", 5);
$ebook->displayInfo();
Output:
Title: Advanced PHP, Author: Jane Smith, File Size: 5 MB
1.3 Polymorphism
Same method behaves differently based on the object.
classDiagram
class Shape {
+void draw()
}
class Circle {
+void draw()
+String type
}
class Square {
+void draw()
+int sideLength
}
Shape <|-- Circle
Shape <|-- SquareExample: Override draw()
class Circle {
public function draw() {
echo "Drawing a circle\n";
}
}
class Square {
public function draw() {
echo "Drawing a square\n";
}
}
function drawShape(Shape $shape) {
$shape->draw();
}
$circle = new Circle();
$square = new Square();
drawShape($circle); // Output: Drawing a circle
drawShape($square); // Output: Drawing a square
2. Advanced File Handling
PHP can read/write files, directories, and sessions.
2.1 File Operations
sequenceDiagram
participant PHP
participant File
PHP->>File: fopen("file.txt", "r")
File-->>PHP: File handle
PHP->>File: fread(handle, 100)
File-->>PHP: Content
PHP->>File: fclose(handle)Example: Read/Write a File
// Write to file
$file = fopen("data.txt", "w");
fwrite($file, "Hello, PHP File Handling!");
fclose($file);
// Read from file
$file = fopen("data.txt", "r");
echo fread($file, filesize("data.txt"));
fclose($file);
Output:
Hello, PHP File Handling!
2.2 Directory Handling
if (is_dir("uploads")) {
echo "Directory exists!";
} else {
mkdir("uploads", 0777);
}
Example: List Files in a Directory
$files = scandir("uploads");
foreach ($files as $file) {
if ($file != "." && $file != "..") {
echo $file . "<br>";
}
}
2.3 Sessions
Sessions store user data across pages.
sequenceDiagram
participant User
participant Server
User->>Server: Start session (session_start())
Server->>User: Assign session ID (cookie)
User->>Server: Submit form
Server->>User: Retrieve session data ($_SESSION)Example: Session-Based Login
// Start session
session_start();
// Set session variable
$_SESSION["user"] = "admin";
// Retrieve session variable
echo "Welcome, " . $_SESSION["user"];
3. Security Concepts
3.1 SQL Injection Prevention
Vulnerable Code:
$username = $_POST["username"];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query); // UNSAFE!
Secure Code (Prepared Statements):
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
3.2 Cross-Site Scripting (XSS) Prevention
Vulnerable Code:
echo $_POST["comment"]; // Outputs raw user input
Secure Code:
echo htmlspecialchars($_POST["comment"], ENT_QUOTES, "UTF-8");
3.3 Cross-Site Request Forgery (CSRF) Prevention
Use CSRF tokens in forms:
session_start();
if (empty($_SESSION["csrf_token"])) {
$_SESSION["csrf_token"] = bin2hex(random_bytes(32));
}
?>
<form method="post">
<input type="hidden" name="csrf_token" value="<?= $_SESSION["csrf_token"] ?>">
<button type="submit">Submit</button>
</form>
Verify on server:
if ($_POST["csrf_token"] !== $_SESSION["csrf_token"]) {
die("CSRF token mismatch!");
}
4. Advanced Arrays
4.1 Multidimensional Arrays
$books = [
["PHP", "John Doe"],
["Java", "Alice Smith"],
["Python", "Bob Johnson"]
];
foreach ($books as $book) {
echo $book[0] . " by " . $book[1] . "<br>";
}
Output:
PHP by John Doe
Java by Alice Smith
Python by Bob Johnson
4.2 Associative Arrays (Key-Value Pairs)
$bookAuthors = [
"PHP" => "John Doe",
"Java" => "Alice Smith"
];
foreach ($bookAuthors as $title => $author) {
echo "$title: $author<br>";
}
5. Error Handling
Use try-catch for exceptions:
try {
$file = fopen("nonexistent.txt", "r");
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
In the Real World
eSewa/Khalti (Payment Gateways)
- OOP: Uses classes like
TransactionandUserto manage payments securely. - Security: Prevents SQL injection by using prepared statements when processing transactions.
- OOP: Uses classes like
Daraz (E-commerce)
- Sessions: Tracks user carts and login states across pages.
- File Handling: Stores product images in directories and session data in temporary files.
Pathao (Ride-Hailing)
- Polymorphism: Different vehicle types (bike, car) inherit from a base
Vehicleclass. - Error Handling: Gracefully manages API failures when fetching driver locations.
- Polymorphism: Different vehicle types (bike, car) inherit from a base
Worked Example: Secure User Registration
Scenario: A user submits a registration form. Validate input, hash passwords, and store securely.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = password_hash($_POST["password"], PASSWORD_BCRYPT);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email!");
}
// Insert into database (prepared statement)
$stmt = $conn->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $password, $email);
$stmt->execute();
// Set session
$_SESSION["user"] = $username;
header("Location: dashboard.php");
}
?>
<form method="post">
<input type="text" name="username" placeholder="Username" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<input type="email" name="email" placeholder="Email" required><br>
<button type="submit">Register</button>
</form>
Exam Tip
- OOP: Always define classes with
__construct()and useextends/implements. - Security: Never trust user input—sanitize, validate, and use prepared statements.
- Sessions: Start with
session_start()and store sensitive data securely. - Arrays: Know when to use indexed vs. associative arrays (e.g., associative for key-value pairs).
- Error Handling: Use
try-catchfor database operations and file handling. - Past Questions: Expect 10-15 marks on security (SQL injection, XSS) and 5-10 marks on OOP/file handling.
Visual Summary
mindmap
root((Advanced PHP))
OOP
Classes & Objects
Inheritance
Polymorphism
Security
SQL Injection
XSS Prevention
CSRF Tokens
File Handling
Read/Write Files
Directory Operations
Sessions
Arrays
Multidimensional
Associative
Error Handling
try-catchBased on the TU BITM syllabus for Web Programming II (IT219), unit 8.
Discussion
Loading…