π§© 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.txtusingFILE_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.