Web Technology IIUnit 412 min read
PHP Arrays & File Handling: Syntax, Operations & Security
Unit 4 of Web Technology II covers PHP arrays (indexed, associative, multidimensional) and file handling (reading, writing, uploading), including error handling, security risks, and real-world applications in web forms, logs, and dynamic content generation.
TAKEAWAYS:
- PHP arrays store multiple values in a single variable using indexed or associative keys, and support nested structures for complex data.
- File handling in PHP involves opening, reading, writing, and closing files using functions like
fopen(),fread(),fwrite(), andfclose(). - Error handling with
@ortry-catchprevents crashes when files are missing or permissions fail. - Security risks like directory traversal attacks can be mitigated by validating file paths and using
basename(). - Real-world uses include processing user uploads (e.g., Daraz product images), logging system activities (e.g., Ncell transaction records), and generating dynamic reports (e.g., NEPSE stock data).
- Multidimensional arrays and file operations enable efficient data storage and retrieval in web applications.
PHP Arrays: Types, Syntax, and Operations
1. Types of Arrays
PHP supports three main array types, each with unique use cases:
classDiagram
class IndexedArray {
+keys: 0, 1, 2, ...
+values: Any data type
+Example: $fruits = ["apple", "banana"]
}
class AssociativeArray {
+keys: Named strings
+values: Any data type
+Example: $person = ["name" => "Rohan", "age" => 25]
}
class MultidimensionalArray {
+keys: Nested arrays
+values: Arrays or scalars
+Example: $matrix = [[1, 2], [3, 4]]
}
IndexedArray --> "Uses" Array
AssociativeArray --> "Uses" Array
MultidimensionalArray --> "Uses" ArrayIndexed Arrays
- Use numeric keys (starting at
0). - Ideal for lists where order matters (e.g., shopping cart items).
- Example:
$colors = ["red", "green", "blue"]; echo $colors[1]; // Output: green
Associative Arrays
- Use string keys (e.g.,
"name","email"). - Perfect for structured data like user profiles or configuration settings.
- Example:
$user = ["id" => 101, "name" => "Priya", "role" => "admin"]; echo $user["name"]; // Output: Priya
Multidimensional Arrays
- Arrays inside arrays, forming tables or trees.
- Used for complex data like nested comments or hierarchical menus.
- Example:
$students = [ ["name" => "Rohan", "marks" => 85], ["name" => "Sita", "marks" => 92] ]; echo $students[1]["name"]; // Output: Sita
2. Common Array Functions
PHP provides built-in functions to manipulate arrays efficiently:
| Function | Purpose | Example |
|---|---|---|
count($array) |
Returns the number of elements. | count($fruits) → 3 |
array_push() |
Adds an element to the end. | array_push($fruits, "orange") |
array_pop() |
Removes the last element. | array_pop($fruits) → "blue" |
array_merge() |
Combines two or more arrays. | array_merge([1, 2], [3]) → [1, 2, 3] |
array_keys() |
Returns all keys. | array_keys($user) → ["id", "name"] |
array_values() |
Returns all values. | array_values($user) → [101, "Priya"] |
in_array($value) |
Checks if a value exists. | in_array("green", $colors) → true |
array_search() |
Finds the key of a value. | array_search("blue", $colors) → 2 |
Worked Example: Shopping Cart Imagine an e-commerce site like Daraz where users add products to a cart. A multidimensional array tracks items, quantities, and prices:
$cart = [
["product" => "Laptop", "quantity" => 1, "price" => 50000],
["product" => "Mouse", "quantity" => 2, "price" => 500]
];
$total = 0;
foreach ($cart as $item) {
$total += $item["quantity"] * $item["price"];
}
echo "Total: ₹" . $total; // Output: ₹51000
3. Looping Through Arrays
Use loops to iterate over arrays and perform operations:
flowchart TD
A["Start"] --> B["Initialize loop\n(e.g., foreach)"]
B --> C["Access current element\n(e.g., $value)"]
C --> D["Process data\n(e.g., echo, calculate)"]
D --> E["Check loop condition"]
E -->|"True"| C
E -->|"False"| F["End"]foreach Loop
Best for reading array elements:
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
// Output:
// apple
// banana
// cherry
for Loop
Useful when you need the index:
for ($i = 0; $i < count($fruits); $i++) {
echo "Index " . $i . ": " . $fruits[$i] . "<br>";
}
Worked Example: NEPSE Stock Data A financial dashboard might display stock prices using an associative array:
$stocks = [
"NTC" => 120.50,
"Ncell" => 850.75,
"NMB" => 320.25
];
echo "<h3>Today's Stock Prices</h3>";
foreach ($stocks as $company => $price) {
echo "$company: ₹$price<br>";
}
File Handling in PHP
File handling allows PHP to interact with files on the server, enabling tasks like logging, configuration, and user uploads.
1. File Operations
PHP uses file handles to read/write files. Key functions:
| Function | Purpose | Example |
|---|---|---|
fopen() |
Opens a file and returns a handle. | $file = fopen("data.txt", "r"); |
fread() |
Reads from a file. | fread($file, 100); |
fwrite() |
Writes to a file. | fwrite($file, "Hello"); |
fclose() |
Closes a file handle. | fclose($file); |
file_get_contents() |
Reads entire file into a string. | $content = file_get_contents("data.txt"); |
file_put_contents() |
Writes a string to a file. | file_put_contents("log.txt", "Error"); |
file_exists() |
Checks if a file exists. | file_exists("config.ini") → true |
Modes for fopen():
"r": Read-only (fails if file doesn’t exist)."w": Write-only (creates file if it doesn’t exist; erases content)."a": Append-only (creates file if it doesn’t exist; adds to end)."r+": Read and write."x": Write-only (fails if file exists).
2. Reading a File
Example: Log File Analysis
A bank like Nabil Bank might log transactions in transactions.log. To read it:
$logFile = fopen("transactions.log", "r");
if ($logFile) {
while (!feof($logFile)) { // Loop until end of file
$line = fgets($logFile);
echo htmlspecialchars($line) . "<br>";
}
fclose($logFile);
} else {
echo "Error: Could not open log file.";
}
3. Writing to a File
Example: User Uploads (e.g., Daraz Product Images) When a user uploads an image, PHP saves it to a directory:
$uploadDir = "uploads/";
$fileName = basename($_FILES["image"]["name"]);
$targetPath = $uploadDir . $fileName;
if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetPath)) {
file_put_contents("upload_log.txt", date("Y-m-d H:i:s") . " - " . $fileName . " uploaded\n", FILE_APPEND);
echo "File uploaded successfully!";
} else {
echo "Error uploading file.";
}
4. Error Handling
Always validate file operations to avoid crashes:
Method 1: @ Operator (Suppress Errors)
$file = @fopen("nonexistent.txt", "r");
if (!$file) {
echo "File not found!";
}
Method 2: try-catch (Exception Handling)
try {
if (!file_exists("config.ini")) {
throw new Exception("Config file missing!");
}
$config = parse_ini_file("config.ini");
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Security Risks and Best Practices
1. Directory Traversal Attacks
Attackers exploit poorly validated file paths to access sensitive files (e.g., /etc/passwd).
Mitigation:
- Use
basename()to strip directory paths:$safeFile = basename($_FILES["upload"]["name"]); - Restrict uploads to specific directories:
$allowedTypes = ["jpg", "png", "gif"]; $fileExt = strtolower(pathinfo($safeFile, PATHINFO_EXTENSION)); if (!in_array($fileExt, $allowedTypes)) { die("Invalid file type!"); }
2. File Permissions
Ensure PHP has write permissions for directories:
chmod 755 uploads/ # Owner: read/write/execute; Others: read/execute
3. Sanitizing File Content
Use htmlspecialchars() when displaying file content to prevent XSS:
echo htmlspecialchars(file_get_contents("data.txt"));
In the Real World
eSewa and Khalti (Payment Processing)
- Idea Used: Associative Arrays
- How: When a user pays for a bill (e.g., NTC or NEPSE), the system stores transaction details in an associative array:
$transaction = [ "user_id" => 12345, "amount" => 500, "service" => "NTC Bill", "status" => "completed", "timestamp" => "2024-05-20 14:30:00" ]; - The array is later logged to a file (
transactions_2024-05.log) for record-keeping.
Pathao (Ride Queue Management)
- Idea Used: Multidimensional Arrays + File Handling
- How: Pathao’s backend maintains a queue of ride requests as a multidimensional array:
$rideQueue = [ ["user_id" => 101, "pickup" => "Kathmandu", "destination" => "Lalitpur", "time" => "15:45"], ["user_id" => 102, "pickup" => "Bhaktapur", "destination" => "Nepalgunj", "time" => "16:00"] ]; - When a driver accepts a ride, the entry is removed from the array and logged to
ride_logs.txtfor analytics.
Daraz (Product Inventory)
- Idea Used: Indexed Arrays + File Handling
- How: Daraz stores product inventory in a large indexed array:
$inventory = [ 0 => ["id" => "P1001", "name" => "Smartphone", "stock" => 50, "price" => 25000], 1 => ["id" => "P1002", "name" => "Laptop", "stock" => 30, "price" => 80000] ]; - When a user places an order, the stock is updated in the array, and the change is written to
inventory_backup.csvfor recovery.
Exam Tip
Arrays:
- Memorize the syntax for indexed, associative, and multidimensional arrays.
- Practice looping (
foreach,for) and common functions (count(),array_push(),in_array()). - Exam Question Type: Given an array, write code to:
- Add/remove elements.
- Search for a value.
- Calculate totals (e.g., cart subtotal).
File Handling:
- Know the modes of
fopen()("r","w","a") and their effects. - Understand error handling (
@,try-catch,file_exists()). - Exam Question Type: Write code to:
- Read a file line by line.
- Append data to a log file.
- Validate and sanitize user uploads.
- Know the modes of
Security:
- Always validate file paths (
basename()). - Restrict file permissions (e.g.,
chmod 755). - Exam Question Type: Identify vulnerabilities in given code (e.g., directory traversal) and suggest fixes.
- Always validate file paths (
Real-World Scenarios:
- Expect questions linking arrays/files to e-commerce (Daraz), payments (eSewa), or logging (Ncell).
- Example: "How would you store and retrieve user orders in a PHP array? Write code to log orders to a file."
Visual Summary:
mindmap
root((PHP Arrays & File Handling))
Arrays
Indexed
Associative
Multidimensional
File Operations
fopen()
fread()/fwrite()
file_get_contents()
Security
Directory Traversal
Permission Checks
Real-World
eSewa Transactions
Daraz Inventory
Pathao Ride QueueBased on the TU BIM syllabus for Web Technology II (IT239), unit 4.
Discussion
Loading…