PHP Reading and Writing Files
PHP file reading and writing example for beginners
Working with files is an essential part of PHP development. Whether you’re building a logging system, uploading files, exporting reports, or storing user data, PHP provides powerful built-in functions to read, write, append, and manage files easily.
In this tutorial, you’ll learn:
How PHP interacts with files
How to read files using different methods
How to write and append data to files
Real-world developer examples
Important file-handling functions
Common best practices
File handling is used for:
Storing logs (log.txt)
Exporting data (report.txt, CSV files)
Reading configuration files
Saving form submissions
Reading templates
Processing uploaded files
PHP makes file handling simple with clear functions.
There are multiple ways to read a file. Here are the most commonly used methods.
Reads and outputs the file content directly to the browser.
readfile("data.txt");
Useful for small files.
$content = file_get_contents("data.txt");
echo $content;
Best when you need file contents stored in a variable.
$lines = file("data.txt");
foreach ($lines as $line) {
echo $line . "<br>";
}
Great for processing line-based data.
$handle = fopen("data.txt", "r");
$content = fread($handle, filesize("data.txt"));
fclose($handle);
echo $content;
More control over file reading.
You can create new files or write to existing ones.
$data = "Hello, this is a new message!";
file_put_contents("output.txt", $data);
This creates the file if it does not exist.
file_put_contents("output.txt", "\nNew Line Added", FILE_APPEND);
$handle = fopen("output.txt", "w"); // w = write
fwrite($handle, "Writing using fwrite() function.");
fclose($handle);
Modes like w, a, r+, w+ provide flexibility.
| Mode | Description |
|---|---|
r |
Read only |
w |
Write (truncate file) |
a |
Append |
r+ |
Read & write |
w+ |
Read & write (truncate file) |
a+ |
Read & append |
if (file_exists("data.txt")) {
echo "File found!";
} else {
echo "File does not exist.";
}
if (file_exists("old.txt")) {
unlink("old.txt");
}
$name = $_POST['name'];
$email = $_POST['email'];
$entry = "Name: $name | Email: $email\n";
file_put_contents("submissions.txt", $entry, FILE_APPEND);
echo "Data saved successfully!";
This is commonly used in feedback forms.
$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData, true);
print_r($data);
$data = ["name" => "Shubham", "role" => "Developer"];
file_put_contents("data.json", json_encode($data));
Always check if a file exists before reading
Close file handles after fopen()
Use file permissions wisely
Sanitize user input when writing to files
Avoid handling extremely large files without buffering
PHP provides a powerful set of functions to read, write, append, and manage files easily. Whether you're logging data, processing uploaded files, or exporting reports, mastering PHP file handling is an essential skill for backend development.