Files are a vital part of every website. Whether you’re saving user feedback, uploading photos, or generating reports, file handling allows your PHP application to store, read, and update information efficiently.
PHP provides built-in functions to create, read, write, and delete files easily. Understanding file handling is essential for building interactive applications where data needs to persist even after the user leaves the page.
Why File Handling Matters
When Vrinda builds a feedback system, she might want to save user comments to a file instead of a database. Similarly, Ananya could generate daily logs for her website’s visitors. File handling makes these tasks simple and effective.
With PHP file functions, you can:
-
Store data in text or CSV files
-
Read or display content from existing files
-
Append new data without overwriting old content
-
Delete or rename files when needed
Understanding PHP File Functions
PHP provides several key functions for file handling:
| Function |
Purpose |
fopen() |
Opens a file |
fclose() |
Closes an open file |
fread() |
Reads data from a file |
fwrite() |
Writes data into a file |
file_exists() |
Checks if a file exists |
unlink() |
Deletes a file |
Let’s go through these step-by-step.
Opening a File
To work with a file, you first need to open it using the fopen() function.
<?php
$file = fopen("example.txt", "r"); // open file in read mode
?>
The fopen() function requires two parameters:
-
File name
-
Mode (how you want to open it)
File Modes in PHP
| Mode |
Description |
r |
Read-only; starts at the beginning of the file |
w |
Write-only; erases existing content or creates a new file |
a |
Write-only; appends data to the end of the file |
x |
Creates a new file for writing; returns an error if file exists |
r+ |
Read and write; starts at the beginning of the file |
w+ |
Read and write; overwrites existing content |
a+ |
Read and write; appends data if the file exists |
For example, Riya wants to open a file in write mode to save her notes:
<?php
$file = fopen("notes.txt", "w");
fwrite($file, "Riya is learning PHP File Handling.");
fclose($file);
?>
This code creates a new file notes.txt if it doesn’t exist and writes the sentence into it.
Reading from a File
Let’s say Ananya created a file named message.txt containing a welcome message. She can read it using fopen() and fread().
<?php
$file = fopen("message.txt", "r");
$content = fread($file, filesize("message.txt")); // read full file
fclose($file);
echo $content;
?>
Here, filesize() tells PHP how many bytes to read. This way, the whole content is read and displayed.
Writing to a File
You can write data using the fwrite() function.
<?php
$file = fopen("data.txt", "w");
fwrite($file, "This file is created by Ananya.\n");
fclose($file);
echo "Data written successfully!";
?>
This will overwrite the file if it already exists. If you want to append data instead of overwriting, open it in append mode (a).
<?php
$file = fopen("data.txt", "a");
fwrite($file, "Vrinda added another line.\n");
fclose($file);
?>
Now, the new line will be added at the end of the file without deleting the old content.
Checking if a File Exists
Before opening or deleting a file, it’s good practice to check if it exists using file_exists().
<?php
if (file_exists("data.txt")) {
echo "File exists!";
} else {
echo "File not found!";
}
?>
If Riya runs this code and data.txt exists, she’ll get the message “File exists!”.
Deleting a File
To delete a file, use the unlink() function.
<?php
if (file_exists("old_data.txt")) {
unlink("old_data.txt");
echo "File deleted successfully.";
} else {
echo "File does not exist.";
}
?>
This is useful when cleaning up temporary or outdated files.
Reading File Line by Line
Sometimes, you don’t need the entire file at once. You can read it line by line using fgets().
<?php
$file = fopen("notes.txt", "r");
while (!feof($file)) { // loop until end of file
echo fgets($file) . "<br>";
}
fclose($file);
?>
If Vrinda wrote multiple lines in her notes file, this will display each line separately on a webpage.
Example: Writing User Feedback to a File
Here’s a practical example. Suppose Ananya creates a simple feedback form.
feedback.html
<form action="save_feedback.php" method="post">
Name: <input type="text" name="name"><br>
Feedback: <textarea name="feedback"></textarea><br>
<input type="submit" value="Submit">
</form>
save_feedback.php
<?php
$name = $_POST['name'];
$feedback = $_POST['feedback'];
$file = fopen("feedback.txt", "a"); // open file in append mode
fwrite($file, "Name: $name\nFeedback: $feedback\n\n");
fclose($file);
echo "Thank you, $name! Your feedback has been saved.";
?>
Whenever a user submits feedback, the data is added to feedback.txt.
Each new entry is written on a new line without overwriting the old ones.
File Handling with Error Checking
It’s good practice to check for errors when opening files.
<?php
$file = @fopen("missing.txt", "r") or die("Unable to open file!");
?>
The @ suppresses warnings, and die() displays a custom message if the file can’t be opened.
If the file doesn’t exist, the script will stop and show “Unable to open file!”
Security Tips for File Handling
-
Validate user input: Never trust filenames from user input. Always sanitize them.
-
Use proper permissions: Make sure your files are not publicly writable.
-
Avoid including user-uploaded files directly: This prevents malicious code execution.
-
Keep sensitive files outside the web root: Store configuration or log files in secure directories.
Real-Life Example: Logging User Activity
If Riya wants to log whenever a user visits her site:
<?php
date_default_timezone_set("Asia/Kolkata");
$log = "User visited on " . date("Y-m-d H:i:s") . "\n";
$file = fopen("visits.log", "a");
fwrite($file, $log);
fclose($file);
?>
Each time someone visits, this code adds a new timestamp to visits.log.
Later, she can analyze this file to see daily or weekly traffic.
Summary of the Tutorial
PHP file handling allows you to work with files easily — whether you’re reading, writing, or deleting them.
You learned how to:
-
Open and close files with fopen() and fclose()
-
Write and append data with fwrite()
-
Read file content using fread() and fgets()
-
Check for existence and delete files with file_exists() and unlink()
These functions are the building blocks of many features such as logs, uploads, reports, and configuration systems.