Web Technology IIUnit 916 min read

Project Work & Implementation in Web Tech

Unit 9 of Web Technology II covers end-to-end project development, integrating HTML, PHP, JavaScript, databases, and security into a real-world web application. Students learn to design, implement, test, and deploy a functional project while addressing challenges like user authentication, data validation, and performan

Project Work Overview

A web project in this unit is a complete, functional application that combines:

  • Frontend: HTML, CSS, JavaScript (dynamic UI).
  • Backend: PHP (logic, processing).
  • Database: MySQL (data storage).
  • Security: Input validation, session management, SQL injection prevention.

Key Phases of a Web Project

flowchart LR
    A["1. Planning"] --> B["2. Design"]
    B --> C["3. Development"]
    C --> D["4. Testing"]
    D --> E["5. Deployment"]
    E --> F["6. Maintenance"]

1. Planning the Project

Step 1: Define Requirements

  • Functional Requirements: What the app must do (e.g., user login, product search, order processing).
  • Non-Functional Requirements: Performance (speed), security (data protection), usability (mobile-friendly).
  • Example: For an e-commerce site (like Daraz), requirements include:
    • User registration/login.
    • Product catalog with search/filter.
    • Shopping cart and checkout.
    • Admin dashboard for inventory management.

Step 2: Choose a Project Idea

Project Type Example Tech Stack
E-commerce Online bookstore PHP, MySQL, Bootstrap, PayPal API
Social Network Classmate forum PHP, JavaScript, MySQL, AJAX
Blog Platform Student blog with comments PHP, MySQL, jQuery, CKEditor
Task Management To-do list with deadlines PHP, JavaScript, Bootstrap, Firebase

Real-World Tie:

  • Daraz uses a multi-tier architecture (frontend → backend → database) to handle thousands of orders per second. Their PHP-based backend processes payments, inventory updates, and user sessions securely.

2. Designing the Project

A. Database Design (ER Diagram)

A well-structured database is critical. For an online library system, the key tables might be:

erDiagram
    USER ||--o{ BOOK : "borrows"
    USER {
        int user_id PK
        string name
        string email
        string password
    }
    BOOK {
        int book_id PK
        string title
        string author
        int stock
    }
    BORROW {
        int borrow_id PK
        int user_id FK
        int book_id FK
        date borrow_date
        date return_date
    }

Key Design Rules:

  1. Normalization: Avoid redundancy (e.g., store user details in one table, not repeated in orders).
  2. Relationships: Use FOREIGN KEY constraints (e.g., user_id in BORROW links to USER).
  3. Indexes: Add indexes on frequently queried columns (e.g., email in USER).

B. UI/UX Design (Wireframing)

  • Low-Fidelity Wireframe (sketch on paper):
    • Login page → Dashboard → Product list → Checkout.
  • High-Fidelity Prototype (using tools like Figma or Adobe XD):
    • Mobile-responsive design.
    • Intuitive navigation (e.g., Khalti’s checkout has a 3-step process: select payment method → enter details → confirm).

Example Wireframe for a Blog:



3. Development Phase

A. Frontend Development (HTML, CSS, JavaScript)

  • HTML: Structure (e.g., <form> for user input).
  • CSS: Styling (e.g., Bootstrap for responsive grids).
  • JavaScript: Dynamic behavior (e.g., real-time search like Google’s autocomplete).

Example: Live Search with JavaScript

// Fetch products from PHP backend as user types
document.getElementById("search").addEventListener("keyup", function() {
    let query = this.value;
    fetch(`search.php?q=${query}`)
        .then(response => response.json())
        .then(data => displayResults(data));
});

B. Backend Development (PHP)

  • Key Files:
    • config.php: Database connection.
    • login.php: Handles authentication.
    • process_order.php: Validates and saves orders.

Example: Secure Login System

// login.php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST["email"];
    $password = $_POST["password"];

    // Validate input
    if (empty($email) || empty($password)) {
        die("Fields cannot be empty!");
    }

    // Check database
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user["password"])) {
        $_SESSION["user_id"] = $user["id"];
        header("Location: dashboard.php");
    } else {
        echo "Invalid credentials!";
    }
}

Real-World Tie:

  • Khalti uses PHP sessions to track user logins securely. Their backend validates transactions in real-time to prevent fraud.

C. Database Interaction (PHP + MySQL)

  • Prevent SQL Injection:
    • Use prepared statements (PDO or MySQLi).
    • Never concatenate user input into SQL queries.

Example: Safe Query with PDO

// Safe: Using prepared statements
$stmt = $pdo->prepare("INSERT INTO orders (user_id, amount) VALUES (?, ?)");
$stmt->execute([$user_id, $amount]);

Unsafe (Vulnerable to SQL Injection):

// UNSAFE: Direct concatenation
$sql = "INSERT INTO orders (user_id, amount) VALUES ($user_id, $amount)";

4. Security Considerations

Common Vulnerabilities & Fixes

Vulnerability Example Fix
SQL Injection ' OR '1'='1 in login form Use prepared statements
XSS (Cross-Site Scripting) <script>alert('hack')</script> in comments Sanitize input with htmlspecialchars()
Session Hijacking Stealing session IDs Regenerate session IDs after login
CSRF (Cross-Site Request Forgery) Fake "Transfer Funds" button on a bank site Use CSRF tokens in forms

Example: Sanitizing User Input

$name = htmlspecialchars($_POST["name"], ENT_QUOTES, "UTF-8");

5. Testing the Project

A. Manual Testing

  • Functionality: Does the login work? Can users add items to cart?
  • Edge Cases:
    • Empty fields → Show error.
    • Invalid email → Reject.
    • Special characters in passwords → Allow (but hash securely).

B. Automated Testing (Unit Testing)

  • Use PHPUnit to test functions:
    // Test login function
    public function testValidLogin() {
        $this->assertTrue(login("user@example.com", "password123"));
    }
    

C. User Acceptance Testing (UAT)

  • Get feedback from peers or clients.
  • Example: Test Pathao’s ride-booking flow—does the app show real-time driver locations?

6. Deployment

Options for Hosting

Hosting Type Provider (Nepal/Global) Best For
Shared Hosting Hostinger, NepalHost Small projects (blogs, portfolios)
VPS DigitalOcean, Linode Medium traffic (e-commerce)
Cloud (AWS/Azure) AWS EC2, Google Cloud High traffic (Ncell’s backend)
Local Server XAMPP/WAMP Development/testing

Steps to Deploy on Shared Hosting (e.g., cPanel):

  1. Upload files via FTP (FileZilla).
  2. Import database via phpMyAdmin.
  3. Set file permissions (e.g., 755 for folders, 644 for files).
  4. Test the live URL.

Real-World Tie:

  • Nepal Stock Exchange (NEPSE) uses a highly secure backend deployed on cloud servers to handle real-time stock data. Their system includes:
    • Load balancing (distributes traffic).
    • HTTPS encryption (secure data transfer).
    • Regular backups (prevents data loss).

7. Maintenance & Updates

  • Bug Fixes: Monitor errors (check server logs).
  • Performance Optimization:
    • Cache frequent queries (e.g., SELECT * FROM products).
    • Compress images (use TinyPNG).
  • Security Patches: Update PHP/MySQL regularly.

Example: Optimizing a Slow Query

-- Before: Slow (no index)
SELECT * FROM orders WHERE user_id = 10;

-- After: Fast (indexed column)
CREATE INDEX idx_user_id ON orders(user_id);

In the Real World

  1. eSewa (Nepal)

    • Idea Used: Multi-tier architecture (frontend → PHP backend → MySQL database).
    • How: When you pay a bill, eSewa’s backend validates your transaction, deducts the amount, and updates the utility provider’s database in real-time.
  2. Khalti (Nepal)

    • Idea Used: Secure session management + tokenization.
    • How: After logging in, Khalti generates a session token to track your activity. This token is invalidated after inactivity to prevent hijacking.
  3. Daraz (Nepal)

    • Idea Used: Load balancing + caching.
    • How: During sales (e.g., "Daraz Days"), their servers use load balancers to distribute traffic across multiple machines, ensuring fast response times even with millions of users.

Exam Tip

What to Expect in the Exam

  1. Project Documentation:

    • You may be asked to describe your project’s architecture (e.g., "Explain how your e-commerce site handles payments").
    • Focus on:
      • Database schema (ER diagram).
      • Key PHP functions (e.g., session_start(), prepare()).
      • Security measures (e.g., "How did you prevent SQL injection?").
  2. Code Snippets:

    • Expect short coding questions (e.g., "Write a PHP function to validate an email").
    • Practice:
      • Form validation.
      • Database queries (safe vs. unsafe).
      • Session handling.
  3. Scenario-Based Questions:

    • Example: "A user reports that their cart items disappear after refreshing. How would you debug this?"
    • Answer Structure:
      • Check if items are stored in session or database.
      • Verify session_start() is called on every page.
      • Test with var_dump($_SESSION).
  4. Diagrams:

    • Be ready to draw:
      • A 3-tier architecture (frontend → backend → database).
      • A sequence diagram for a login process.
      • An ER diagram for a simple database (e.g., library system).

Final Checklist Before Submission

Task Done?
Database is normalized ✅
All SQL queries use prepared statements ✅
Sessions are regenerated after login ✅
Input is sanitized (HTML/JS) ✅
Project has a README with setup instructions ✅
Tested on mobile/desktop ✅

Worked Example: Building a Simple Blog

Scenario: Create a blog where users can post articles and comment.

Step 1: Database Design

erDiagram
    USER ||--o{ POST : "writes"
    POST ||--o{ COMMENT : "has"
    USER {
        int id PK
        string name
        string email
    }
    POST {
        int id PK
        int user_id FK
        string title
        text content
        date created_at
    }
    COMMENT {
        int id PK
        int post_id FK
        int user_id FK
        text text
    }

Step 2: Key PHP Files

  1. post.php (Display posts)

    $stmt = $pdo->query("SELECT * FROM posts ORDER BY created_at DESC");
    while ($post = $stmt->fetch()) {
        echo "<h2>{$post['title']}</h2>";
        echo "<p>{$post['content']}</p>";
    }
    
  2. add_post.php (Secure post submission)

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $title = htmlspecialchars($_POST["title"]);
        $content = $_POST["content"];
    
        $stmt = $pdo->prepare("INSERT INTO posts (user_id, title, content) VALUES (?, ?, ?)");
        $stmt->execute([$_SESSION["user_id"], $title, $content]);
    
        header("Location: blog.php");
    }
    

Step 3: Security Measures

  • CSRF Protection: Add a hidden token to forms.
    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
    
  • Password Hashing: Always use password_hash().
    $hashed_password = password_hash($password, PASSWORD_BCRYPT);
    

Step 4: Testing

  • Manual Test: Try posting an article with:
    • Empty title → Should show error.
    • <script>alert('xss')</script> in content → Should be escaped.
  • Automated Test: Use PHPUnit to verify add_post() saves data correctly.

Common Mistakes to Avoid

  1. Hardcoding Database Credentials:

    • ❌ define("DB_HOST", "localhost"); in every file.
    • ✅ Use a config.php file outside the web root.
  2. Not Validating Input:

    • ❌ Trusting $_POST["email"] directly.
    • ✅ Validate with filter_var($email, FILTER_VALIDATE_EMAIL).
  3. Ignoring Session Security:

    • ❌ Relying only on session_start().
    • ✅ Regenerate session ID after login:
      session_regenerate_id(true);
      
  4. Poor Error Handling:

    • ❌ Showing raw MySQL errors to users.
    • ✅ Log errors to a file and show generic messages:
      error_log("Database error: " . $pdo->errorInfo()[2]);
      echo "An error occurred. Please try again.";
      

Real-World Debugging Example

Problem: Users report that their Khalti payments fail intermittently. Debugging Steps:

  1. Check Server Logs: Look for PHP errors (e.g., timeouts).
  2. Test API Endpoint: Use Postman to call Khalti’s API directly.
  3. Verify Session: Ensure the user’s session is active (no token expiry).
  4. Network Latency: If the issue is slow, optimize database queries or use a CDN.

Solution:

  • Implement retry logic in the frontend (e.g., "Payment failed. Retry?").
  • Use webhooks to confirm payment status asynchronously.

Final Project Submission Tips

  1. Document Everything:

    • Include a README.md with:
      • Project description.
      • Setup instructions (e.g., "Import database.sql into phpMyAdmin").
      • Screenshots of key features.
  2. Code Comments:

    • Add comments for complex logic (e.g., # Hash password using BCRYPT).
    • Example:
      // Validate and sanitize email
      $email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);
      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          die("Invalid email format.");
      }
      
  3. Git Repository:

    • Use GitHub/GitLab to track changes.
    • Commit messages should be clear (e.g., "Fixed SQL injection in login.php").

Summary Table: Project Work Checklist

Phase Key Tasks Tools/Tech
Planning Define requirements, choose tech stack Trello, Figma
Design Draw ER diagram, wireframes MySQL Workbench, Lucidchart
Development Write HTML/PHP/JS, connect to database VS Code, XAMPP
Security Sanitize input, use prepared statements, secure sessions htmlspecialchars(), PDO
Testing Manual + automated tests, UAT PHPUnit, BrowserStack
Deployment Upload to hosting, set permissions cPanel, FileZilla
Maintenance Monitor logs, optimize queries, update dependencies New Relic, GitHub

Practice Questions for Exam

  1. Explain the 3-tier architecture of a web application with an example from Daraz.
  2. Write a PHP function to validate a user’s email and password, storing the password securely.
  3. Draw an ER diagram for a "School Management System" with tables for students, courses, and enrollments.
  4. How would you prevent SQL injection in a login form? Provide a code snippet.
  5. Describe the steps to deploy a PHP project on a shared hosting server like NepalHost.

  • Books:
    • PHP and MySQL for Dummies (for beginners).
    • Clean Code (for writing maintainable PHP).
  • Tools:
    • XAMPP/WAMP: Local development.
    • Postman: API testing.
    • GitHub Desktop: Version control.
  • Online:

Based on the TU BIM syllabus for Web Technology II (IT239), unit 9.

Discussion

Loading…