StreetGeek Academy Β· PHP Foundations

🧩 Module 8: Working with Files

Objective: Learn how to create, open, read, write, and delete files in PHP β€” and use them to
store data submitted from users.

πŸ”Ή 1. Why File Handling Matters

Files are essential for:

  • Saving submitted form data
  • Storing logs or backups
  • Reading configurations
  • Exporting reports

🧠 PHP interacts with the file system directly β€” meaning your web app can create, update, or read real files on
your server.

πŸ”Ή 2. Common PHP File Functions

Function Description
fopen() Opens a file (creates it if missing)
fwrite() Writes to a file
fread() Reads file content
fclose() Closes the file
file_get_contents() Reads an entire file easily
file_put_contents() Writes data to a file quickly
unlink() Deletes a file
file_exists() Checks if file exists
filesize() Returns file size (in bytes)

πŸ”Ή 3. Opening and Writing to a File

<?php
$file = fopen("notes.txt", "w"); // "w" = write mode
fwrite($file, "Hello, StreetGeek Academy!");
fclose($file);
echo "File created and written successfully!";
?>

βœ… This creates a file named notes.txt and writes to it.

πŸ“˜ Modes

Mode Meaning
r Read only
w Write only (erases existing content)
a Append (adds to existing content)
r+ Read and write
a+ Read and append

πŸ”Ή 4. Reading from a File

<?php
$file = fopen("notes.txt", "r");
$content = fread($file, filesize("notes.txt"));
fclose($file);

echo nl2br($content); // Keeps line breaks
?>

βœ… Displays the contents of your file.

🧠 nl2br() converts new lines (\n) into HTML <br> tags.

πŸ”Ή 5. Using Shortcuts: file_put_contents() and file_get_contents()

PHP offers simplified helpers for quick file I/O.

Writing:

<?php
file_put_contents("quick.txt", "This is a quick file write example!");
?>

Reading:

<?php
echo file_get_contents("quick.txt");
?>

βœ… Easier than using fopen() and fclose() for small files.

πŸ”Ή 6. Appending to an Existing File

<?php
file_put_contents("notes.txt", "\nAnother line added!", FILE_APPEND);
?>

βœ… Adds content without erasing existing data.

πŸ”Ή 7. Checking and Deleting Files

<?php
if (file_exists("notes.txt")) {
    echo "File exists!";
} else {
    echo "File not found.";
}

unlink("old-file.txt"); // deletes a file
?>

🧠 Always check before deleting to avoid errors.

πŸ”Ή 8. File Upload Handling (Intro)

You can also upload files from forms using the $_FILES superglobal.

<form method="POST" enctype="multipart/form-data" action="">
  Select image: <input type="file" name="upload">
  <input type="submit" value="Upload">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $file = $_FILES["upload"];
    $name = $file["name"];
    $tmp_name = $file["tmp_name"];
    $destination = "uploads/" . $name;

    if (move_uploaded_file($tmp_name, $destination)) {
        echo "File uploaded successfully!";
    } else {
        echo "Upload failed.";
    }
}
?>

βœ… Creates a working file upload system (requires an /uploads/ folder with write permissions).

🧩 Hands-On Practice

Exercise 1: Write and Read (file-demo.php)

<?php
$text = "StreetGeek Academy - PHP File Handling Lesson\n";
file_put_contents("lesson.txt", $text);
echo "File created successfully!<br>";

$content = file_get_contents("lesson.txt");
echo nl2br($content);
?>

Exercise 2: Append (append-demo.php)

<?php
file_put_contents("lesson.txt", "Adding another line.\n", FILE_APPEND);
echo nl2br(file_get_contents("lesson.txt"));
?>

Exercise 3: Delete (delete-demo.php)

<?php
if (file_exists("lesson.txt")) {
    unlink("lesson.txt");
    echo "File deleted successfully!";
} else {
    echo "No file found to delete.";
}
?>

Exercise 4: Write Form Input to File (save-form.php)

<form method="POST" action="">
  Name: <input type="text" name="name"><br>
  Message: <textarea name="message"></textarea><br>
  <input type="submit" value="Save">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $entry = "Name: " . htmlspecialchars($_POST["name"]) .
             "\nMessage: " . htmlspecialchars($_POST["message"]) . "\n\n";
    file_put_contents("messages.txt", $entry, FILE_APPEND);
    echo "<p style='color:green;'>Saved successfully!</p>";
}
?>

Exercise 5: Display Saved Messages (view-messages.php)

<?php
if (file_exists("messages.txt")) {
    echo nl2br(file_get_contents("messages.txt"));
} else {
    echo "No messages yet.";
}
?>

🎯 Mini Project – Guestbook System (guestbook.php)

<h2>StreetGeek Guestbook</h2>

<form method="POST" action="">
  Name: <input type="text" name="name"><br>
  Comment: <textarea name="comment"></textarea><br>
  <input type="submit" value="Post">
</form>

<?php
$filename = "guestbook.txt";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $entry = "<strong>" . htmlspecialchars($_POST["name"]) . "</strong>: " .
             htmlspecialchars($_POST["comment"]) . "\n";
    file_put_contents($filename, $entry, FILE_APPEND);
    echo "<p style='color:green;'>Entry added!</p>";
}

if (file_exists($filename)) {
    echo "<h3>Guestbook Entries:</h3>";
    echo nl2br(file_get_contents($filename));
}
?>

βœ… When users post comments, they are saved and displayed below the form.

🧾 Module 8 Quiz

# Question Options Correct
1 What function is used to open a file? a) open() Β· b) fopen() Β· c) create() b
2 What does "a" mode do in fopen()? a) Read Β· b) Append Β· c) Overwrite b
3 What function writes data quickly? a) write_file() Β· b) file_write() Β· c) file_put_contents() c
4 Which function deletes a file? a) unlink() Β· b) remove() Β· c) delete_file() a
5 What does nl2br() do? a) Converts <br> to \n Β· b) Adds HTML line breaks for newlines Β· c) Removes newlines b

πŸ’ͺ Challenge Task – Form-Based Notes App

Objective: Create a mini note-taking system using file storage in notes.php.

  • Add a form for a title and content field.
  • On submit, save notes to notes.txt using FILE_APPEND.
  • Display all previous notes below the form.
  • Use nl2br() to preserve formatting.
  • Add a β€œClear Notes” button that deletes all entries using unlink().

βœ… Example Output:

  • Note saved successfully!
  • β€”
  • Title: PHP Practice
  • Content: Learning how to use file_put_contents() today.

🧾 Submission Checklist

  • βœ… file-demo.php β†’ creates and reads file
  • βœ… append-demo.php β†’ appends correctly
  • βœ… save-form.php β†’ saves user input
  • βœ… view-messages.php β†’ displays data from file
  • βœ… guestbook.php β†’ working guestbook
  • βœ… Quiz completed

🏁 Next Step: In Module 9, you’ll connect your PHP code to a real database using MySQL β€”
learning how to store and retrieve data dynamically using CRUD operations (Create, Read, Update, Delete).
This is where you’ll start building truly dynamic, full-stack applications.