Mastering PHP File Handling: Read, Write, Append & Delete Files Easily
Last updated 5 months, 2 weeks ago | 355 views 75 5
Introduction: Why PHP File Handling Matters
File handling is a core aspect of backend development. Whether you're reading logs, processing form data, generating reports, or uploading files, you'll need to interact with files on the server.
PHP provides a rich set of built-in file system functions that allow developers to create, open, read, write, append, rename, and delete files. This makes PHP extremely powerful for building dynamic, data-driven websites.
In this article, you'll learn step-by-step how to handle files in PHP safely and efficiently.
Basic Concepts in PHP File Handling
Common PHP File Handling Functions
| Function | Purpose |
|---|---|
fopen() |
Open a file |
fread() |
Read contents from a file |
fwrite() |
Write data to a file |
fclose() |
Close the file handle |
file_get_contents() |
Reads a file into a string |
file_put_contents() |
Writes a string to a file |
unlink() |
Deletes a file |
file_exists() |
Checks if a file exists |
Step-by-Step: PHP File Handling Operations
1. Opening a File with fopen()
$file = fopen("example.txt", "r"); // 'r' = read mode
Modes Explained:
| Mode | Description |
|---|---|
| r | Read only |
| w | Write only; truncate file |
| a | Write only; append if exists |
| x | Create and write; error if exists |
| r+ | Read & write |
2. Reading a File with fread()
$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
fclose($file);
echo $content;
3. Writing to a File with fwrite()
$file = fopen("log.txt", "w");
fwrite($file, "This is a log entry.\n");
fclose($file);
This overwrites any existing content in log.txt.
4. Appending to a File with a Mode
$file = fopen("log.txt", "a");
fwrite($file, "New log entry at " . date("Y-m-d H:i:s") . "\n");
fclose($file);
5. Using file_get_contents() and file_put_contents() (Simplified)
// Read entire file into a string
$data = file_get_contents("example.txt");
// Write a string into a file
file_put_contents("output.txt", "Hello, world!");
These are cleaner alternatives to fopen() for simple use cases.
6. Deleting a File with unlink()
if (file_exists("delete_me.txt")) {
unlink("delete_me.txt");
echo "File deleted.";
} else {
echo "File not found.";
}
✅ Full Working Example
<?php
$file = "data.txt";
// Write to the file
file_put_contents($file, "This is line 1\n");
// Append to the file
file_put_contents($file, "This is line 2\n", FILE_APPEND);
// Read and display contents
if (file_exists($file)) {
$contents = file_get_contents($file);
echo "File Contents:\n" . $contents;
} else {
echo "File not found.";
}
?>
Tips & Common Pitfalls
✅ Best Practices
-
Always close files using
fclose()to free resources. -
Use
file_exists()to avoid errors before accessing files. -
Prefer
file_put_contents()/file_get_contents()for quick operations. -
Use
try-catchwithExceptionhandling in advanced scenarios (custom error handling). -
Set proper file permissions (read/write) on the server.
❌ Common Mistakes
-
Forgetting to check if a file exists before reading it.
-
Using
'w'mode without realizing it deletes existing content. -
Not handling file permission issues (especially on Linux servers).
-
Assuming
fopen()always succeeds—always check the return value.
File Handling Function Comparison
| Task | Traditional Way | Simplified Way |
|---|---|---|
| Read file | fopen() + fread() |
file_get_contents() |
| Write file | fopen() + fwrite() |
file_put_contents() |
| Append | fopen('a') + fwrite() |
file_put_contents(..., FILE_APPEND) |
| Delete file | unlink() |
unlink() |
| Check exists | file_exists() |
file_exists() |
Summary: Best Practices for PHP File Handling
-
PHP provides powerful and flexible file handling capabilities.
-
Use appropriate file modes (
r,w,a, etc.) based on your intent. -
Use simplified functions (
file_get_contents,file_put_contents) when possible. -
Always check if the file exists before operating on it.
-
Be mindful of file permissions and server environment.