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-finally and 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 : Composition
  1. Classes 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!
    
  2. 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
    
  3. Encapsulation

    • Restrict access to data using public, private, or protected.
    class BankAccount {
        private $balance;
        public function deposit($amount) {
            if ($amount > 0) $this->balance += $amount;
        }
        public function getBalance() {
            return $this->balance;
        }
    }
    
  4. 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 exception
  1. Basic Syntax

    try {
        $result = 10 / $zero; // Throws DivisionByZeroError
    } catch (DivisionByZeroError $e) {
        echo "Cannot divide by zero!";
    } finally {
        echo "Operation attempted.";
    }
    
  2. Custom Exceptions

    class InvalidUserException extends Exception {}
    throw new InvalidUserException("Username too short!");
    
  3. 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 data

Example JWT Flow (Khalti API):

  1. User logs in via Khalti’s OAuth.
  2. Khalti returns a JWT token.
  3. 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

  1. Code Tracing: Expect questions where you must trace OOP inheritance or error handling.
    • Example: Given a User class and a Admin subclass, predict the output of $admin->greet().
  2. Security Flaws: Identify vulnerabilities in code snippets (e.g., missing password_hash).
  3. Performance Trade-offs: Compare OPcache vs. database indexing in a scenario.
  4. API Design: Describe how JWT works in a real system (e.g., Daraz’s order API).
  5. 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…