Web Programming IIUnit 410 min read

PHP Arrays & File Handling: Structures, Operations & Security

Unit 4 of Web Programming II covers PHP arrays (indexed, associative, multidimensional) and file handling (opening modes, reading/writing, permissions), with practical examples like sorting, searching, and saving form data to files—essential for dynamic web apps and data storage.

TAKEAWAYS:

  • PHP arrays store data in indexed (numeric keys) or associative (string keys) formats, with multidimensional arrays for nested structures.
  • File handling in PHP requires proper modes (r, w, a, x) and permissions (chmod) to read/write safely.
  • Common array operations include sorting (sort(), asort()), searching (in_array(), array_search()), and merging (array_merge()).
  • Security risks like file inclusion vulnerabilities must be mitigated using basename() and realpath().
  • Real-world uses include user data storage (e.g., saving form submissions to files) and dynamic content generation (e.g., displaying sorted product lists).

1. PHP Arrays: Types, Declaration, and Operations

Arrays are ordered maps (key-value pairs) in PHP, used to store multiple values in a single variable. They come in three types:

1.1 Types of Arrays

classDiagram
    class IndexedArray {
        +Keys: Numeric (0, 1, 2...)
        +Example: $fruits = ["apple", "banana"]
    }
    class AssociativeArray {
        +Keys: String (e.g., "name", "age")
        +Example: $user = ["name" => "Rohan", "age" => 20]
    }
    class MultidimensionalArray {
        +Nested arrays (arrays within arrays)
        +Example: $students = [ ["Rohan", 20], ["Sita", 21] ]
    }
    IndexedArray <|-- MultidimensionalArray
    AssociativeArray <|-- MultidimensionalArray

1.2 Declaring Arrays

  • Indexed Array (numeric keys):
    $fruits = array("Apple", "Banana", "Orange"); // Old syntax
    $fruits = ["Apple", "Banana", "Orange"];     // New syntax (PHP 5.4+)
    
  • Associative Array (string keys):
    $user = [
        "name" => "Rohan",
        "age"  => 20,
        "city" => "Kathmandu"
    ];
    
  • Multidimensional Array (arrays within arrays):
    $students = [
        ["name" => "Rohan", "age" => 20],
        ["name" => "Sita", "age" => 21]
    ];
    

1.3 Key Array Functions

Function Purpose Example
count($array) Returns the number of elements. count($fruits) → 3
array_push() Adds an element to the end. array_push($fruits, "Mango")
array_pop() Removes the last element. array_pop($fruits) → "Orange"
array_shift() Removes the first element. array_shift($fruits) → "Apple"
array_unshift() Adds an element to the beginning. array_unshift($fruits, "Guava")
sort() Sorts indexed arrays in ascending order. sort($fruits)
asort() Sorts associative arrays by value. asort($user)
ksort() Sorts associative arrays by key. ksort($user)
array_search() Searches for a value and returns its key. array_search("Banana", $fruits) → 1
in_array() Checks if a value exists in an array. in_array("Banana", $fruits) → true
array_merge() Merges two or more arrays. array_merge($fruits, ["Grapes"])

1.4 Worked Example: Sorting and Displaying Student Data

Task: Create a 2D array of 5 students and display it in an HTML table.

$students = [
    ["name" => "Rohan", "age" => 20, "city" => "Kathmandu"],
    ["name" => "Sita", "age" => 21, "city" => "Pokhara"],
    ["name" => "Hari", "age" => 19, "city" => "Bhaktapur"],
    ["name" => "Gita", "age" => 22, "city" => "Lalitpur"],
    ["name" => "Ramesh", "age" => 20, "city" => "Dharan"]
];

// Sort by age (ascending)
usort($students, function($a, $b) {
    return $a["age"] <=> $b["age"];
});

Output (HTML Table):

<table border="1">
    <tr><th>Name</th><th>Age</th><th>City</th></tr>
    <?php foreach ($students as $student): ?>
        <tr>
            <td><?php echo $student["name"]; ?></td>
            <td><?php echo $student["age"]; ?></td>
            <td><?php echo $student["city"]; ?></td>
        </tr>
    <?php endforeach; ?>
</table>

Trace (After Sorting):

Name Age City
Hari 19 Bhaktapur
Rohan 20 Kathmandu
Ramesh 20 Dharan
Sita 21 Pokhara
Gita 22 Lalitpur

2. File Handling in PHP

Files allow persistent data storage. PHP provides functions to open, read, write, and close files.

2.1 File Opening Modes

Mode Description
r Read-only (fails if file doesn’t exist).
r+ Read/write (fails if file doesn’t exist).
w Write-only (creates file if it doesn’t exist; erases content).
w+ Read/write (creates file if it doesn’t exist; erases content).
a Write-only (creates file if it doesn’t exist; appends to end).
a+ Read/write (creates file if it doesn’t exist; appends to end).
x Write-only (creates file; fails if file exists).
x+ Read/write (creates file; fails if file exists).

Example: Writing to a File (w+ mode)

$file = fopen("sport.txt", "w+");
fwrite($file, "Cricket match today at 3 PM.\nCricket is fun!\n");
fclose($file);

State After Writing:

sport.txt:
Cricket match today at 3 PM.
Cricket is fun!

2.2 Reading a File

Task: Print the portion of sport.txt between the first two occurrences of "cricket".

$file = fopen("sport.txt", "r");
$content = fread($file, filesize("sport.txt"));
fclose($file);

$lines = explode("\n", $content);
$firstCricket = strpos(strtolower($lines[0]), "cricket");
$secondCricket = strpos(strtolower($lines[1]), "cricket");

if ($firstCricket !== false && $secondCricket !== false) {
    echo "Portion between 'cricket':\n";
    echo substr($lines[0], $firstCricket + 8); // +8 to skip "cricket "
    echo "\n" . $lines[1];
}

Output:

Portion between 'cricket':
 match today at 3 PM.
Cricket is fun!

2.3 File Permissions

Check and modify file permissions using:

// Check permissions (returns octal, e.g., 0644)
$permissions = fileperms("sport.txt");
echo "Permissions: " . decoct($permissions); // Output: 0644

// Change permissions (e.g., to 0755)
chmod("sport.txt", 0755);

3. Real-World Applications

In the Real World

  1. eSewa (Nepal):

    • Uses associative arrays to store user transaction data (e.g., ["user_id" => 123, "amount" => 500]).
    • File handling logs transactions in transactions.log for auditing.
  2. Khalti (Nepal):

    • Multidimensional arrays manage merchant data (e.g., [["merchant_id" => 1, "name" => "Daraz"], ["merchant_id" => 2, "name" => "Pathao"]]).
    • File operations write payment receipts to receipts/{user_id}.txt.
  3. NTC Website (Nepal):

    • Array sorting displays train schedules in ascending order (e.g., sort($trains)).
    • File reading loads routes.txt to populate dropdown menus for station selection.

Worked Example: Saving Form Data to a File (Like eSewa/Khalti)

Task: Create a web form to save user data to Person.txt.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $age = $_POST["age"];
    $gender = $_POST["gender"];

    $file = fopen("Person.txt", "a");
    fwrite($file, "$name,$age,$gender\n");
    fclose($file);
    echo "Data saved successfully!";
}
?>

HTML Form:

<form method="post">
    Name: <input type="text" name="name"><br>
    Age: <input type="number" name="age"><br>
    Gender:
    <input type="radio" name="gender" value="Male"> Male
    <input type="radio" name="gender" value="Female"> Female<br>
    <input type="submit" value="Submit">
</form>

State After Submission (File Person.txt):

Rohan,20,Male
Sita,21,Female

4. Security Considerations

4.1 File Inclusion Vulnerabilities

Avoid unsafe file operations like:

// UNSAFE: Allows directory traversal attacks
include($_GET["page"] . ".php");

// SAFE: Uses basename() to prevent traversal
include(basename($_GET["page"]) . ".php");

4.2 Generating Unique IDs

Use uniqid() or random_int():

$uniqueId = uniqid("user_", true); // e.g., "user_5f8d3a1b"
$randomId = random_int(1000, 9999); // e.g., 4273

Exam Tip

  1. Array Questions:

    • Memorize count(), sort(), asort(), array_search() for sorting/searching.
    • For 2D arrays, use foreach loops to iterate and usort() for custom sorting.
  2. File Handling:

    • Modes matter! w erases files; a appends. Always close files with fclose().
    • For file content extraction, use explode() (split lines) and strpos() (find substrings).
  3. Common Pitfalls:

    • Off-by-one errors in loops (e.g., for ($i=0; $i<=count($array); $i++) → wrong!).
    • Forgetting fclose() can lead to memory leaks.
    • Unsafe file operations (e.g., include() without basename()) are easy marks for security questions.

Practice Questions:

  1. Write a PHP program to merge two associative arrays and display the result.
  2. How would you find the length of a multidimensional array?
  3. Explain the difference between file_get_contents() and fopen() + fread().
  4. Write a function to generate a unique filename (e.g., user_123_20230515.txt).

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

Discussion

Loading…