Web Technology IIUnit 87 min read
Advanced PHP Security & Performance: OOP, Error Handling, Encryption & APIs
Unit 8 of Web Technology II explores PHP’s advanced features—object-oriented programming (OOP), robust error handling, data encryption, secure API design, and performance optimization—with real-world security threats like SQL injection and XSS, plus best practices for building scalable web applications.
TAKEAWAYS:
- OOP in PHP transforms code into reusable classes/objects with inheritance, encapsulation, and polymorphism, drastically improving maintainability.
- Error handling uses
try-catch-finallyand custom exceptions to gracefully manage runtime errors, logging them for debugging while shielding users. - Data encryption (hashing, salting, HTTPS) protects sensitive data like passwords and payment details from breaches.
- Secure API design enforces authentication (JWT/OAuth), input validation, and rate limiting to prevent abuse.
- Performance tuning leverages caching (OPcache), database indexing, and lazy loading to optimize slow queries and high-traffic apps.
- Security threats (XSS, CSRF, session hijacking) require defensive coding like output escaping and CSRF tokens.
Core Concepts: OOP in PHP
PHP supports Object-Oriented Programming (OOP), a paradigm that organizes code into classes (blueprints) and objects (instances). This reduces redundancy and improves scalability.
Key OOP Features in PHP
classDiagram
class Class {
+String $name
+__construct(String name)
+display() void
}
class Child extends Class {
+String $role
+__construct(String name, String role)
+displayRole() void
}
Class <|-- Child : Inheritance
Class --> "1" Class : CompositionClasses and Objects
- A class defines properties (attributes) and methods (functions).
- An object is an instance of a class.
class User { public $name; public function __construct($name) { $this->name = $name; } public function greet() { return "Hello, $this->name!"; } } $user = new User("Rohan"); echo $user->greet(); // Output: Hello, Rohan!Inheritance
- A child class (
extends) inherits properties/methods from a parent class.
class Admin extends User { public function manage() { return "$this->name is managing the system."; } } $admin = new Admin("Priya"); echo $admin->greet(); // Inherited echo $admin->manage(); // Child method- A child class (
Encapsulation
- Restrict access to data using
public,private, orprotected.
class BankAccount { private $balance; public function deposit($amount) { if ($amount > 0) $this->balance += $amount; } public function getBalance() { return $this->balance; } }- Restrict access to data using
Polymorphism
- Override parent methods or use interfaces.
interface Logger { public function log($message); } class FileLogger implements Logger { public function log($message) { file_put_contents('log.txt', $message); } }
Error Handling: try-catch-finally
PHP uses structured error handling to manage exceptions gracefully.
How It Works
stateDiagram-v2
[*] --> TryBlock : Start
TryBlock --> CatchBlock : Exception thrown
CatchBlock --> FinallyBlock : Handle error
FinallyBlock --> [*] : Cleanup
TryBlock --> FinallyBlock : No exceptionBasic Syntax
try { $result = 10 / $zero; // Throws DivisionByZeroError } catch (DivisionByZeroError $e) { echo "Cannot divide by zero!"; } finally { echo "Operation attempted."; }Custom Exceptions
class InvalidUserException extends Exception {} throw new InvalidUserException("Username too short!");Logging Errors Use
error_log()to record errors in a file:error_log("Error: " . $e->getMessage(), 3, "errors.log");
Data Security: Encryption and Hashing
1. Password Hashing (with Salting)
Never store plain-text passwords. Use password_hash() and password_verify():
$hashed = password_hash("mypassword123", PASSWORD_BCRYPT);
if (password_verify("mypassword123", $hashed)) {
echo "Password matches!";
}
2. HTTPS and Encryption
- HTTPS encrypts data in transit using SSL/TLS.
- AES-256 encrypts sensitive data (e.g., payment details):
$encrypted = openssl_encrypt("secret", "AES-256-CBC", "key"); $decrypted = openssl_decrypt($encrypted, "AES-256-CBC", "key");
3. SQL Injection Prevention
Use Prepared Statements with PDO:
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
Secure API Design
APIs must authenticate users, validate inputs, and limit requests.
1. Authentication: JWT (JSON Web Tokens)
sequenceDiagram
User->>API: Login (email/password)
API->>Database: Verify credentials
Database-->>API: Return user ID
API->>User: Issue JWT token
User->>API: Include token in header
API->>User: Return protected dataExample JWT Flow (Khalti API):
- User logs in via Khalti’s OAuth.
- Khalti returns a JWT token.
- Token is sent with each API request to verify identity.
2. Rate Limiting
Prevent abuse with header("X-RateLimit-Limit: 100") and tracking requests in a database.
3. Input Validation
Sanitize all inputs:
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email) throw new InvalidArgumentException("Invalid email!");
Performance Optimization
1. OPcache
Enable PHP’s built-in opcode cache:
; php.ini
opcache.enable=1
opcache.memory_consumption=128
2. Database Indexing
Add indexes to frequently queried columns:
CREATE INDEX idx_email ON users(email);
3. Lazy Loading
Load data only when needed (e.g., in loops):
foreach ($products as $product) {
echo $product->name;
// Load details only if clicked
}
Real-World Applications
1. eSewa (Nepal)
- OOP: Uses classes to manage user sessions, transactions, and payment gateways.
- Security: Encrypts payment data with HTTPS and PCI-DSS compliance.
- Performance: Caches frequent queries (e.g., user profiles) with OPcache.
2. Khalti API
- JWT Authentication: Secures API calls for merchants.
- Rate Limiting: Prevents brute-force attacks on payment endpoints.
- Input Validation: Rejects malformed requests (e.g., invalid amounts).
3. Nepal Stock Exchange (NEPSE) Website
- Error Handling: Logs and displays user-friendly messages for failed trades.
- Database Security: Uses prepared statements to prevent SQL injection in stock queries.
Exam Tip
- Code Tracing: Expect questions where you must trace OOP inheritance or error handling.
- Example: Given a
Userclass and aAdminsubclass, predict the output of$admin->greet().
- Example: Given a
- Security Flaws: Identify vulnerabilities in code snippets (e.g., missing
password_hash). - Performance Trade-offs: Compare OPcache vs. database indexing in a scenario.
- API Design: Describe how JWT works in a real system (e.g., Daraz’s order API).
- SQL Injection: Always use PDO/prepared statements—this is a high-weight topic.
Worked Example: Bank Loan Interest Calculation
class Loan {
private $principal;
private $rate;
private $time;
public function __construct($principal, $rate, $time) {
$this->principal = $principal;
$this->rate = $rate;
$this->time = $time;
}
public function calculateInterest() {
return $this->principal * $this->rate * $this->time / 100;
}
}
$loan = new Loan(100000, 8.5, 2);
echo "Interest: $" . $loan->calculateInterest(); // Output: $1700
Real-World Tie: Nabil Bank uses OOP to model loans, mortgages, and interest calculations securely.
Based on the TU BIM syllabus for Web Technology II (IT239), unit 8.
Discussion
Loading…