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

FunctionDescription
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

ModeMeaning
rRead only
wWrite only (erases existing content)
aAppend (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

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

💪 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.