Web Technology IIUnit 410 min read
PHP Server-Side Scripting: Basics, Syntax & Database Interaction
Unit 4 of Web Technology II introduces PHP as a server-side scripting language, covering core syntax, form handling, database connectivity, and security fundamentals. Learn how PHP processes user input, interacts with databases, and generates dynamic web content—essential for building modern web applications like e-com
TAKEAWAYS:
- PHP executes on the server before sending HTML to the client, enabling dynamic content generation (e.g., personalized user dashboards).
- Server-side scripts handle sensitive tasks like authentication, database queries, and file operations securely (unlike client-side JavaScript).
- PHP integrates with MySQL/MariaDB via
mysqlior PDO for CRUD operations, using SQL queries embedded in PHP code. - Key syntax includes variables (
$var), conditionals (if/else), loops (foreach), and functions to modularize logic. - Security best practices (e.g., prepared statements, input validation) prevent SQL injection and XSS attacks in real-world apps.
- PHP scripts are embedded in HTML using
<?php ... ?>tags and processed by the web server (Apache/Nginx) before rendering.
1. What is Server-Side Scripting?
Server-side scripting runs on the web server (not the user’s browser) to generate dynamic content. Unlike client-side languages (JavaScript), PHP processes data before sending HTML to the user. This is critical for:
- Authentication (e.g., login forms in eSewa).
- Database interactions (e.g., Daraz order processing).
- File handling (e.g., uploading profile pictures in Facebook).
sequenceDiagram
participant User
participant Browser
participant WebServer
participant PHP
participant Database
User->>Browser: Sends HTTP request (e.g., "login.php?user=ram")
Browser->>WebServer: Forwards request to PHP interpreter
WebServer->>PHP: Executes script (validates credentials, queries DB)
PHP->>Database: Runs SQL (e.g., "SELECT * FROM users WHERE username='ram'")
Database-->>PHP: Returns user data
PHP->>WebServer: Generates HTML (e.g., "Welcome, Ram!")
WebServer-->>Browser: Sends HTML to user
Browser->>User: Displays dynamic page
Note right of User: **Server-side processing**
Note right of PHP: PHP executes on server
Note right of Database: Database interactionServer-side request flow for a login system (eSewa-style)sequenceDiagram
User->>Browser: Sends HTTP request (e.g., "login.php?user=ram")
Browser->>Web Server: Forwards request to PHP interpreter
Web Server->>PHP: Executes script (validates credentials, queries DB)
PHP->>Database: Runs SQL (e.g., "SELECT * FROM users WHERE username='ram'")
Database-->>PHP: Returns user data
PHP->>Web Server: Generates HTML (e.g., "Welcome, Ram!")
Web Server-->>Browser: Sends HTML to user
Browser->>User: Displays dynamic page2. PHP Basics: Syntax and Structure
A. Embedding PHP in HTML
PHP code is embedded using <?php ... ?> tags. Example:
<!DOCTYPE html>
<html>
<head><title>BIT Web Tech</title></head>
<body>
<?php
echo "<h1>Welcome to PHP!</h1>";
$name = "Ram";
echo "<p>Name: $name</p>"; // Output: Name: Ram
?>
</body>
</html>
B. Variables and Data Types
PHP variables start with $ and are loosely typed:
$age = 25; // Integer
$price = 19.99; // Float
$isLoggedIn = true; // Boolean
$name = "Ram"; // String
C. Comments
// Single-line comment
# Alternative single-line
/*
Multi-line
comment
*/
3. Handling User Input (Forms)
PHP processes form data via $_POST or $_GET superglobal arrays. Example:
<form method="post" action="process.php">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Login</button>
</form>
process.php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
// Validate and redirect
header("Location: home.php");
exit();
}
?>
REAL WORLD:
- eSewa: Uses PHP to validate user credentials and redirect to the dashboard after login.
- Khalti: Processes payment forms server-side to securely store transaction data in databases.
4. Database Connectivity with PHP
PHP connects to databases using MySQLi or PDO. Example with MySQLi:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "BIT_DB";
```mermaid
erDiagram
USERS ||--o{ ORDERS : places
USERS {
int id PK
string username
string password_hash
string email
datetime created_at
}
ORDERS {
int id PK
int user_id FK
string product_name
float amount
datetime order_date
}
USERS ||--o{ PAYMENTS : makes
PAYMENTS {
int id PK
int order_id FK
string method
float amount
datetime paid_at
}
Database schema for an e-commerce system (Daraz-like)
// Create connection $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully!"; $conn->close(); ?>
#### **Querying a Database**
```php
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
}
REAL WORLD:
- Nepal Stock Exchange (NEPSE): Uses PHP to fetch and display real-time stock prices from a MySQL database.
- Banking systems: PHP scripts validate loan applications and update customer records in databases.
5. Security Best Practices
A. SQL Injection Prevention
Vulnerable code:
$sql = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "'";
Fixed (using prepared statements):
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
B. Input Validation
$username = trim($_POST['username']);
if (!preg_match("/^[a-zA-Z0-9_]+$/", $username)) {
die("Invalid username!");
}
REAL WORLD:
- Pathao: Validates driver locations and passenger requests to prevent fraud.
- NTC: Uses input validation to process online bill payments securely.
6. PHP Configuration (php.ini)
Key settings:
| Setting | Purpose |
|---|---|
display_errors |
Controls whether errors are shown to users (set to Off in production). |
variables_order |
Defines the order of superglobal arrays (e.g., EGPCS for $_ENV, $_GET, etc.). |
request_order |
Specifies the order in which PHP reads input data (e.g., GP for $_GET then $_POST). |
7. Worked Example: Login System
HTML Form (login.html):
<form method="post" action="login.php">
Username: <input type="text" name="user"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" value="Login">
</form>
PHP Script (login.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = $_POST["user"];
$pass = $_POST["pass"];
```figure
{"type":"network","nodes":["Client","Web Server","PHP Script","Database","Session Storage"],"edges":[["Client","Web Server","HTTP Request"],["Web Server","PHP Script","Processes Login"],["PHP Script","Database","Query"],["Database","PHP Script","Result"],["PHP Script","Session Storage","Sets Session"],["PHP Script","Web Server","Redirects to Home"],["Web Server","Client","HTML Response"]],"directed":true,"highlight":[["PHP Script","Database"],["PHP Script","Session Storage"]],"caption":"Login system workflow (Khalti-style)"}
// Check against database (simplified)
if ($user == "admin" && $pass == "1234") {
session_start();
$_SESSION["loggedin"] = true;
header("Location: home.php");
} else {
echo "Invalid credentials!";
}
} ?>
REAL WORLD:
- Khalti’s login: Uses PHP to verify user credentials against a hashed password database (never store plaintext passwords!).
8. Common PHP Functions
| Function | Purpose |
|---|---|
array_splice() |
Inserts/removes array elements. |
extract() |
Converts array to variables (e.g., $array = ["name" => "Ram"] → $name = "Ram"). |
compact() |
Opposite of extract() (creates array from variables). |
json_encode()/decode() |
Converts JSON to PHP arrays/objects and vice versa. |
Example with array_splice():
$fruits = ["Apple", "Banana", "Orange"];
array_splice($fruits, 1, 0, "Mango"); // Insert "Mango" at index 1
print_r($fruits); // Output: ["Apple", "Mango", "Banana", "Orange"]
Exam Tip
- Always validate input: Use
trim(),filter_var(), and regex to sanitize data. - Use prepared statements: Never concatenate user input directly into SQL queries.
- Redirect after form submission: Use
header("Location: ...")to avoid resubmission issues. - Practice database queries: Know how to
SELECT,INSERT, andUPDATEusing PHP + MySQL. - Debugging: Enable
display_errorsin development (php.ini) but disable it in production. - Session management: Use
session_start()for user-specific data (e.g., logged-in status).
Visual Summary:
classDiagram
class PHP {
+Embedded in HTML
+Handles $_POST/$_GET
+Connects to MySQL
+Secure with prepared statements
}
class MySQL {
+Stores user data
+Executes SQL queries
}
class User {
+Submits form data
+Sees dynamic content
}
User --> PHP : Sends input
PHP --> MySQL : Queries database
PHP --> User : Returns HTMLIn the real world
- eSewa: Uses PHP server-side scripting to validate user credentials (username/password) against a MySQL database, then generates a secure session token for authenticated access to transaction history.
- Nepal Stock Exchange (NEPSE): PHP scripts fetch real-time stock prices from a database and dynamically render HTML tables for investors, ensuring data consistency and security with prepared SQL statements.
- Pathao: PHP handles driver location validation and passenger request processing, using server-side logic to prevent fraudulent bookings and update ride statuses in real-time.
Based on the TU BIT syllabus for Web Technology II (BIT301), unit 4.
Discussion
Loading…