IT219 Web Programming II

Web Programming IIUnit 911 min read

Project Work & Practical Implementation in Web Dev

Unit 9 of Web Programming II synthesizes all prior PHP/JavaScript concepts into hands-on projects, teaching agile workflows, debugging, deployment, and real-world case studies like eSewa’s payment gateways or Daraz’s inventory systems.

TAKEAWAYS

  • A web project lifecycle follows planning (requirements, wireframes), development (coding, testing), and deployment (hosting, maintenance).
  • Agile methodologies (sprints, backlogs) accelerate iterative development, unlike waterfall’s rigid phases.
  • Debugging tools (Xdebug, browser DevTools) and version control (Git) are critical for collaborative projects.
  • Deployment involves choosing platforms (shared vs. VPS hosting) and optimizing performance (caching, CDNs).
  • Security hardening (OWASP checks, input sanitization) is mandatory for production apps.
  • Real-world tie-ins: eSewa’s PHP backend, Pathao’s ride-matching algorithms, and NEPSE’s stock-trading dashboards all use these principles.

1. The Web Project Lifecycle

A web project isn’t just code—it’s a systematic process from idea to live service. Break it into phases:

Phase 1: Planning & Requirements

  • Stakeholder analysis: Who uses the app? (e.g., Daraz’s buyers vs. sellers)
  • Functional vs. non-functional requirements:
    • Functional: User login, product search.
    • Non-functional: Load time <2s, 99.9% uptime.
  • Wireframing: Sketch UI layouts (use tools like Figma or Balsamiq).
flowchart TD
    A["Stakeholder Meetings"] --> B["Gather Requirements: Functional (e.g., User login, Product search) & Non-functional (e.g., Load time <2s, 99.9% uptime)"]
    B --> C["Define Scope: Project boundaries, timelines, resources"]
    C --> D["Create Wireframes: Low-fidelity UI sketches (e.g., Figma/Balsamiq)"]
    D --> E["Prototype: Interactive mockup for stakeholder review"]

Phase 2: Development

  • Tech stack selection:
    • Frontend: HTML/CSS + JavaScript (or frameworks like React).
    • Backend: PHP (with Laravel/Symfony) or Node.js.
    • Database: MySQL/PostgreSQL.
  • Modular coding: Split logic into reusable components (e.g., a PaymentGateway class for eSewa).
  • Version control: Use Git with branches (main, dev, feature/payment).

Phase 3: Testing

  • Unit tests: Test individual functions (e.g., validateEmail()).
  • Integration tests: Ensure PHP backend + MySQL work together.
  • User acceptance testing (UAT): Let stakeholders test (e.g., NTC’s customer portal).
  • Debugging tools:
    • Xdebug for PHP: Attach debugger to track variable states.
    • Browser DevTools: Inspect network requests (e.g., API calls to Khalti).

2. Agile vs. Waterfall: A Comparison

Aspect Agile Waterfall
Flexibility Iterative (sprints), adaptable Rigid phases
Delivery Frequent small releases One big release at the end
Feedback Continuous stakeholder input Late-stage feedback
Tools Jira, Trello, GitHub Projects Gantt charts, MS Project
Example Pathao’s ride-matching updates NEPSE’s legacy stock system

Agile wins for dynamic projects (e.g., YouTube’s algorithm tweaks), while waterfall suits regulated systems (e.g., bank loan processing).


3. Debugging & Error Handling

Common PHP Errors

Error Cause Fix
Undefined index Missing $_GET/$_POST key Add isset() checks
SQL injection Unsanitized user input Use prepared statements
500 Server Error Syntax error in .php file Check error logs (error_log)

Debugging Workflow

  1. Reproduce the error: Note steps to trigger it (e.g., "After clicking ‘Checkout’").
  2. Check logs: error_log or Xdebug’s variable watch.
  3. Isolate the issue: Comment out code sections to narrow it down.
  4. Fix and test: Verify the patch doesn’t break other features.
Error log0Browser console1Xdebug trace2Database query3
Debugging tools prioritization: Browser console (step 2) for frontend errors.

Example: A Daraz order fails if inventory > stock.

// Before (vulnerable)
if ($userInput > $stock) {
    $order->place(); // Boom!
}

// After (safe)
if ($userInput <= $stock) {
    $order->place();
}

4. Deployment Strategies

static/assetsdynamic/apistatic/index.htmlwww.pathao.comv1/ridev1/paymentv1/userapi.pathao.comRoot Domain (e.g., pathao.com)
Example domain structure for a ride-hailing app (CDN, API separation).

Hosting Options

Type Pros Cons Example
Shared Hosting Cheap ($2–$10/month) Limited resources Ncell’s old website
VPS Full control (e.g., Ubuntu + Nginx) Higher cost ($10–$50/month) eSewa’s backend
Cloud (AWS) Scalable (auto-scaling) Complex setup Google’s global services

Deployment Steps (Example: Deploying a PHP App to a VPS)

  1. Set up server:
    sudo apt update
    sudo apt install apache2 php mysql-server
    
  2. Upload code via Git or SFTP:
    git push origin main
    
  3. Configure .htaccess for URL routing.
  4. Test locally first (use localhost with XAMPP).
  5. Monitor with tools like New Relic.

5. Security Hardening

OWASP Top 10 for PHP

  1. Injection: Always use prepared statements.
    // UNSAFE
    $query = "SELECT * FROM users WHERE email = '$email'";
    
    // SAFE
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    
  2. Broken Authentication: Use sessions + CSRF tokens.
  3. Sensitive Data Exposure: Encrypt passwords with password_hash().
  4. XML External Entities (XXE): Validate XML inputs.

Real-World Example: eSewa’s Security

  • Problem: Phishing attacks via fake login pages.
  • Solution: Implement HSTS headers and 2FA.

6. Performance Optimization

Techniques

  • Caching: Store frequent queries (e.g., Daraz’s product listings).
    // Cache for 1 hour
    $cache = file_get_contents('cache/product_list.json');
    
  • CDNs: Serve static assets (images, JS) from global servers (e.g., Cloudflare).
  • Database indexing: Speed up searches (e.g., NEPSE’s stock symbol lookups).

7. Case Study: Building a Pathao-like Ride-Matching App

Requirements

  • Users request rides via a web app.
  • Drivers accept/reject requests in real time.
  • Payment processed via Khalti/eSewa.

Tech Stack

  • Frontend: HTML/CSS + JavaScript (fetch API for real-time updates).
  • Backend: PHP (Laravel) + MySQL.
  • Real-time: WebSockets (Ratchet library).

Key Features

  1. Driver Assignment Algorithm:
1.21.50.80.30.5UserDriver 1Driver 2Driver 3
Distance-based driver assignment (km). Driver 3 (0.8km) selected.
  1. Database Schema:
    CREATE TABLE drivers (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(100),
      location POINT  -- Stores GPS coordinates
    );
    

Deployment

  • Host backend on a VPS (DigitalOcean).
  • Use Redis for caching driver locations.
  • Monitor with Prometheus.

8. Exam Tips

  1. Show the lifecycle: Draw a mermaid flowchart of planning → development → testing → deployment.
  2. Compare Agile vs. Waterfall: Use the table above; mention sprints and backlogs.
  3. Debugging question: Given a PHP error, trace it step-by-step (e.g., Notice: Undefined variable → check isset()).
  4. Security: Always mention prepared statements and CSRF tokens.
  5. Real-world link: Connect to eSewa’s payment gateway or Pathao’s ride-matching logic.
  6. Code snippet: Write a 10-line PHP function (e.g., inventory check) and trace its execution.

Visuals

  1. Project Lifecycle Flowchart (above, in Phase 1).
  2. Agile vs. Waterfall Table (above).
  3. PHP Debugging Example (code + error table).
  4. Pathao Algorithm Flowchart (above).
  5. Database Schema (SQL snippet with POINT type for GPS).
  6. Deployment Checklist (mermaid diagram of server setup steps).

In the Real World

  1. eSewa’s Payment Gateway

    • Idea: Uses PHP sessions to track user transactions across pages.
    • How: When you click "Pay," eSewa stores a session ID to verify the payment later. If the session expires, the payment fails (security measure).
    • Worked Example: If you abandon your Daraz cart, eSewa’s session expires, and you must re-authenticate to resume checkout.
  2. Pathao’s Ride-Matching Algorithm

    • Idea: Implements a priority queue (heap) to assign drivers based on proximity.
    • How: Pathao’s backend sorts drivers by distance (using GPS coordinates) and assigns the closest available driver. This is a greedy algorithm in real time.
    • Worked Example: If you request a ride at Thapathali, Pathao’s system checks all drivers within 1 km first, then 2 km, etc., ensuring the fastest match.
  3. NEPSE’s Stock Trading Dashboard

    • Idea: Uses PHP + MySQL triggers to update stock prices in real time.
    • How: When a stock price changes (e.g., Ncell’s IPO), NEPSE’s backend runs a stored procedure to update the database and refresh the dashboard for all users simultaneously.
    • Worked Example: If you’re monitoring NEPSE’s live feed, the dashboard updates every 5 seconds because the backend polls the exchange API and caches results in Redis.

Worked Example: Debugging a PHP Session Issue

Scenario: Users log out unexpectedly on eSewa’s mobile app.

Steps to Debug:

  1. Check session config:
    // Ensure session settings are correct
    ini_set('session.gc_maxlifetime', 14400); // 4 hours
    session_start();
    
  2. Verify session storage:
    • Is it using files (session.save_path) or Redis?
    • If files, check permissions (chmod 777 /tmp).
  3. Trace the flow:
    • Add error_log(session_id()) to see if the ID persists.
    • If session_id() is empty, the session was destroyed.

Fix:

// Add this to prevent session timeout
session_set_cookie_params(0, '/', '', true, true);
session_start();

State After Fix:

  • Session ID remains consistent across pages.
  • User stays logged in until manual logout.

Based on the TU BITM syllabus for Web Programming II (IT219), unit 9.

Discussion

Loading…