Web TechnologyUnit 511 min read
Server-Side Scripting, Databases & Web Architecture
Unit 5 of Web Technology covers how server-side scripts (PHP, Node.js) process requests, interact with databases (MySQL, SQLite), manage sessions/cookies, and build dynamic web apps—with real-world examples from eSewa, Daraz, and Ncell.
TAKEAWAYS:
- Server-side scripts execute on the web server (not the user’s browser) to handle logic, validate data, and interact with databases.
- Sessions track user-specific data across pages (unlike cookies, which are client-side and vulnerable to tampering).
- Databases store structured data (e.g., user profiles, orders) using SQL queries (SELECT, INSERT, UPDATE).
- Web servers process HTTP requests/responses in a request-response cycle (e.g., Daraz’s order processing).
- Security best practices include input validation, prepared statements (to prevent SQL injection), and HTTPS.
- Real-world apps use server-side scripting for tasks like eSewa’s payment validation, Pathao’s ride dispatching, and Ncell’s billing systems.
1. What is Server-Side Programming?
Server-side programming refers to scripts executed on the web server (not the user’s browser) to:
- Process form data (e.g., login credentials, order details).
- Interact with databases (store/retrieve data).
- Generate dynamic content (e.g., personalized dashboards).
- Manage user sessions (track logged-in users).
How It Works: Client-Server Interaction
sequenceDiagram
participant User as Client (Browser)
participant Server as Web Server (e.g., Apache, Nginx)
participant DB as Database (MySQL, SQLite)
User->>Server: HTTP Request (e.g., POST /login)
Server->>Server: Run PHP/Node.js script
Server->>DB: Query (SELECT * FROM users WHERE email=...)
DB-->>Server: Result (user data)
Server->>User: HTTP Response (HTML, JSON)Real Picture:
2. Key Server-Side Technologies
| Technology | Purpose | Example Use Case | Nepal Example |
|---|---|---|---|
| PHP | Server-side scripting (most common) | eSewa’s payment processing | eSewa’s backend |
| Node.js | JavaScript runtime for servers | Daraz’s real-time order tracking | Daraz’s backend services |
| Python (Django/Flask) | Rapid development | Ncell’s customer portal | Ncell’s billing system |
| MySQL/SQLite | Database storage | Storing user profiles, transactions | NEPSE’s stock data |
| Apache/Nginx | Web server software | Hosting all TU/PU exam portals | TU’s official website |
3. Database Interaction: SQL Basics
Databases store structured data (e.g., user accounts, orders). Server-side scripts use SQL to:
- Retrieve data:
SELECT * FROM users WHERE email='user@example.com' - Insert data:
INSERT INTO orders (user_id, amount) VALUES (1, 5000) - Update data:
UPDATE products SET stock=stock-1 WHERE id=101
Example: Storing User Data (From Past Exams)
Task: Design a form to store name, email, phone, gender, country with validation rules.
Solution:
<?php
// Database connection (MySQLi)
$conn = new mysqli("localhost", "root", "", "store");
// Validate and insert data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
// ... (validate phone, gender, country)
$sql = "INSERT INTO information (name, email, phone, gender, country)
VALUES ('$name', '$email', '$phone', '$gender', '$country')";
if ($conn->query($sql)) {
echo "Data saved!";
}
}
?>
Validation Rules (from past exams):
- All fields are required.
- Phone must be 10 digits.
- Email must follow
user@domain.comformat.
Real Example:
- Pathao’s Ride Dispatching:
When you book a ride, the server validates your location, checks driver availability (via
SELECT * FROM drivers WHERE status='available'), and updates the database with your order (INSERT INTO rides (user_id, driver_id, status)).
4. Sessions vs. Cookies
| Feature | Sessions | Cookies |
|---|---|---|
| Storage | Server-side (stored in server memory) | Client-side (stored in browser) |
| Security | More secure (harder to tamper) | Vulnerable to XSS attacks |
| Persistence | Expires when browser closes | Can be set to expire later |
| Use Case | Tracking logged-in users | Remembering preferences (e.g., "Stay signed in") |
How Sessions Work (Step-by-Step)
stateDiagram-v2
[*] --> UserOpensSite: User visits website
UserOpensSite --> SessionCreated: Server creates session ID
SessionCreated --> SessionStored: Session ID sent to client (cookie)
SessionStored --> UserActions: User interacts (e.g., clicks "Add to Cart")
UserActions --> SessionUpdated: Server updates session data
SessionUpdated --> [*]: Session expires (after timeout)Example: Login System Without Database
<?php
session_start(); // Start session
if ($_POST["login"]) {
$username = $_POST["username"];
$password = $_POST["password"];
// (In real apps, verify against a database!)
$_SESSION["user"] = $username; // Store in session
header("Location: dashboard.php");
}
if (isset($_SESSION["user"])) {
echo "Welcome, " . $_SESSION["user"];
} else {
echo "Please log in.";
}
?>
Logout:
session_unset(); // Clear session
session_destroy(); // End session
Real Example:
- eSewa’s Login: When you log in, eSewa creates a session to track your account. This session is used to authorize transactions (e.g., transferring money) without storing credentials in cookies.
5. Web Server Processing: HTTP Request-Response Cycle
A web server handles requests in this order:
- Receive Request: User submits a form (e.g.,
POST /login). - Parse Request: Server extracts data (e.g.,
username=john). - Execute Script: Run PHP/Node.js to validate data.
- Query Database: Fetch/update data (e.g., check if user exists).
- Generate Response: Send HTML/JSON back to the client.
Example: Daraz Order Processing
sequenceDiagram
participant User as Customer
participant Server as Daraz Backend
participant DB as Database
User->>Server: POST /checkout (order_id=123, items=[...])
Server->>DB: SELECT * FROM products WHERE id IN (items)
DB-->>Server: Product details
Server->>Server: Validate stock, calculate total
Server->>DB: UPDATE products SET stock=stock-1
Server->>DB: INSERT INTO orders (user_id, total, status)
Server->>User: HTTP 200 (Success + order confirmation)Common HTTP Methods:
| Method | Purpose | Example |
|---|---|---|
| GET | Retrieve data | GET /products?id=101 |
| POST | Submit data (e.g., forms) | POST /login (with credentials) |
| PUT | Update existing data | PUT /users/1 (update profile) |
| DELETE | Remove data | DELETE /cart/5 |
6. Security Best Practices
A. SQL Injection Prevention
Vulnerable Code (❌):
$sql = "SELECT * FROM users WHERE email='" . $_POST["email"] . "'";
Fixed Code (✅):
$stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
$stmt->bind_param("s", $_POST["email"]);
$stmt->execute();
B. Input Validation
Always validate user input:
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if (!$email) {
die("Invalid email!");
}
C. HTTPS (Encryption)
- Use HTTPS (not HTTP) to encrypt data in transit.
- Example: Ncell’s billing portal uses HTTPS to protect transaction details.
7. Real-World Applications in Nepal
| Company/App | Server-Side Role | Technology Used |
|---|---|---|
| eSewa | Validates payments, updates transaction logs | PHP + MySQL |
| Pathao | Matches riders/drivers, tracks orders | Node.js + MongoDB |
| Daraz | Processes orders, manages inventory | Java/Spring + PostgreSQL |
| Ncell | Handles billing, customer data | Python (Django) + Oracle |
| NEPSE | Displays stock prices, logs trades | Java + SQL Server |
Worked Example: Ncell Billing System
- User Action: You top-up ₹500 via Ncell’s website.
- Server-Side Steps:
- Validate your phone number and amount.
- Deduct from your account (
UPDATE accounts SET balance=balance-500 WHERE phone='98XXXXXXXX'). - Add to the transaction log (
INSERT INTO transactions (phone, amount, type)). - Send SMS confirmation (via API).
- Database Tables:
CREATE TABLE accounts ( phone VARCHAR(15) PRIMARY KEY, balance DECIMAL(10,2) ); CREATE TABLE transactions ( id INT AUTO_INCREMENT PRIMARY KEY, phone VARCHAR(15), amount DECIMAL(10,2), type ENUM('topup', 'payment'), timestamp TIMESTAMP );
8. Common Exam Questions & How to Answer
Q1: "Explain how sessions work. Write a script to create/remove sessions."
Answer Structure:
- Definition: Sessions track user-specific data server-side.
- How It Works:
session_start()initializes a session.- Data stored in
$_SESSIONarray. - Session ID sent to client via cookie.
- Script Example (as shown above in Section 4).
- Comparison with Cookies (table in Section 4).
Q2: "Design a form to store user data with validation and database storage."
Answer Structure:
- HTML Form (with
requiredattributes):<form method="POST" action="process.php"> Name: <input type="text" name="name" required><br> Email: <input type="email" name="email" required><br> <!-- Other fields --> <input type="submit" value="Submit"> </form> - PHP Validation (check for empty fields, valid email, phone format).
- SQL Query (INSERT with prepared statements).
- Database Schema (table structure for
information).
Q3: "How does a web server process HTTP requests?"
Answer Structure:
- Request-Response Cycle (diagram in Section 5).
- Steps:
- Parse HTTP method (GET/POST).
- Execute server-side script.
- Query database if needed.
- Generate response (HTML/JSON).
- Example: Daraz order processing (sequence diagram in Section 5).
Exam Tip
For Scripting Questions:
- Always show full code (HTML + PHP/Node.js).
- Include input validation and database queries.
- Use prepared statements to avoid SQL injection.
For Conceptual Questions:
- Draw diagrams (sequence diagrams for HTTP, state diagrams for sessions).
- Compare sessions vs. cookies (table format).
- Relate to real-world apps (eSewa, Pathao, Ncell).
Common Mistakes to Avoid:
- Forgetting
session_start()in session examples. - Using concatenated SQL (vulnerable to injection).
- Not validating user input (e.g., missing
requiredin forms).
- Forgetting
Final Visual Summary:
mindmap
root((Server-Side Programming))
Technologies
PHP
Node.js
Python (Django/Flask)
Databases
MySQL
SQLite
SQL Queries (SELECT, INSERT, UPDATE)
Sessions
Server-side storage
$_SESSION array
More secure than cookies
Security
SQL Injection Prevention
Input Validation
HTTPS
Real-World
eSewa (Payments)
Pathao (Ride Matching)
Ncell (Billing)Based on the TU BCA syllabus for Web Technology (CACS205), unit 5.
Discussion
Loading…