PHP File Handling
PHP file handling is used to create, read, write, append, and delete files on the server. It is useful when you want to store logs, save small text content, read configuration files, or process file-based data.
PHP gives many built-in file functions. The common ones are fopen(), fwrite(), fgets(), file_get_contents(), file_put_contents(), and fclose(). The official PHP manual has a full list of filesystem functions.
Quick Answer
To handle a file in PHP, open the file, perform the required operation, and close it after use.
<?php
$file = fopen("notes.txt", "a");
if ($file === false) {
die("Unable to open file.");
}
fwrite($file, "New log entry" . PHP_EOL);
fclose($file);
?>
This example opens notes.txt in append mode, writes a new line, and closes the file.
Understanding PHP File Modes
The second parameter of fopen() is the file mode. It decides how the file will be opened.
| Mode | Description |
|---|---|
r |
Read only. File must already exist. |
r+ |
Read and write. File must already exist. |
w |
Write only. Creates a new file or clears existing content. |
w+ |
Read and write. Creates a new file or clears existing content. |
a |
Append mode. Adds content at the end of the file. |
a+ |
Read and append. |
x |
Creates a new file. Fails if the file already exists. |
x+ |
Read and write. Creates a new file only if it does not exist. |
For most practical cases:
- Use
rto read a file - Use
wto overwrite a file - Use
ato append content safely
Reading a File in PHP
You can read file content using fopen() with fgets() or use the shorter file_get_contents() function.
Read a File Line by Line
<?php
$file = fopen("sample.txt", "r");
if ($file === false) {
die("Unable to open file.");
}
while (($line = fgets($file)) !== false) {
echo htmlspecialchars($line) . "<br>";
}
fclose($file);
?>
This method is memory efficient for large files.
Read Entire File Content
<?php
$content = file_get_contents("sample.txt");
if ($content === false) {
die("Unable to read file.");
}
echo nl2br(htmlspecialchars($content));
?>
file_get_contents() is simpler and good for small or medium-sized files.
If you are working with uploaded files, you may also like this guide on PHP file upload.
Writing to a File in PHP
Use fwrite() when you want full control over file writing operations.
<?php
$file = fopen("notes.txt", "w");
if ($file === false) {
die("Unable to open file.");
}
$text = "PHP file handling example.";
fwrite($file, $text);
fclose($file);
echo "File written successfully.";
?>
The w mode clears existing content before writing new data.
Append Data to a File
<?php
$file = fopen("logs.txt", "a");
if ($file === false) {
die("Unable to open file.");
}
$logMessage = date("Y-m-d H:i:s") . " User logged in" . PHP_EOL;
fwrite($file, $logMessage);
fclose($file);
echo "Log added successfully.";
?>
Append mode is commonly used for logs and activity tracking.

Writing and appending file content using PHP
Using file_put_contents() in PHP
PHP also provides a shorter way to write content into a file using file_put_contents().
<?php
$data = "Welcome to PHP file handling.";
$result = file_put_contents("message.txt", $data);
if ($result === false) {
echo "Failed to write file.";
} else {
echo "File written successfully.";
}
?>
This function automatically opens, writes, and closes the file.
Append Content with file_put_contents()
<?php
$log = date("Y-m-d H:i:s") . " New visitor" . PHP_EOL;
file_put_contents(
"visitor-log.txt",
$log,
FILE_APPEND
);
echo "Log updated successfully.";
?>
The FILE_APPEND flag adds new content at the end without removing existing data.
Check Whether a File Exists
Before reading or deleting a file, it is good practice to check whether the file exists.
<?php
$filePath = "sample.txt";
if (file_exists($filePath)) {
echo "File exists.";
} else {
echo "File not found.";
}
?>
This helps avoid warnings and improves error handling.
Delete a File in PHP
Use the unlink() function to delete a file.
<?php
$filePath = "old-log.txt";
if (file_exists($filePath)) {
unlink($filePath);
echo "File deleted successfully.";
} else {
echo "File does not exist.";
}
?>
Be careful while deleting files. Always validate the file path before calling unlink().
Create and Read Files with a Simple PHP Demo
The downloadable project included with this tutorial contains a small PHP demo application.
Features included:
- Create a text file
- Write content into the file
- Append additional content
- Read file content
- Delete the file
- Basic error handling
The demo uses plain PHP without frameworks. The UI is intentionally simple so the file handling logic remains easy to understand.
Placeholder for screenshot
- Image filename: php-file-handling-demo-form.webp
- Alt text: PHP file handling demo application interface
- SEO caption: Simple PHP file handling demo for reading and writing files
- Capture: Show the demo page with textarea input, action buttons, and output message
Get File Size in PHP
You can use filesize() to get the size of a file in bytes.
<?php
$filePath = "sample.txt";
if (file_exists($filePath)) {
echo filesize($filePath) . " bytes";
}
?>
Rename a File in PHP
The rename() function changes the file name.
<?php
rename("old-name.txt", "new-name.txt");
echo "File renamed successfully.";
?>
Copy a File in PHP
You can duplicate an existing file using copy().
<?php
copy("source.txt", "backup.txt");
echo "File copied successfully.";
?>
This is useful for creating backups before modifying important files.
Security Considerations
File handling can become risky if user input is directly used in file paths or file names.
Follow these practices while working with files in PHP:
- Do not allow arbitrary file paths from users
- Validate file names before processing
- Avoid storing executable PHP files inside writable directories
- Use proper file permissions on Linux servers
- Escape output when displaying file content in HTML
- Check file existence before reading or deleting
The OWASP Path Traversal guide explains why unrestricted file access can become dangerous in web applications.
Common Errors and Fixes
Permission Denied
This usually happens when PHP does not have write permission for the target directory.
chmod 755 storage
Make sure the web server user can access the folder.
Failed to Open Stream
This error appears when the file path is incorrect or the file does not exist.
<?php
if (!file_exists("data.txt")) {
die("File not found.");
}
?>
Content Overwritten Accidentally
If you use w mode, the existing file content is erased.
Use append mode a if you want to preserve old data.
Developer FAQ
What is the difference between fopen() and file_get_contents()?
fopen() gives more control and is suitable for large files or line-by-line processing. file_get_contents() is shorter and better for quickly reading smaller files.
Which PHP file mode should I use for logging?
Use append mode a. It adds new content without deleting existing log entries.
How do I create a file if it does not exist?
Use w, w+, a, or a+ mode. PHP automatically creates the file if it does not already exist.
Can PHP read large files?
Yes. For large files, read the file line by line using fgets() instead of loading the entire file into memory.
How do I safely display file content in HTML?
Use htmlspecialchars() before outputting file content into the browser.
<?php
echo htmlspecialchars($content);
?>
Can I handle JSON files using PHP file functions?
Yes. You can read JSON files using file_get_contents() and decode them using json_decode().
<?php
$json = file_get_contents("settings.json");
$data = json_decode($json, true);
print_r($data);
?>
If you are working with JSON APIs, you may also like this tutorial on sending JSON data using PHP.
Conclusion
PHP file handling is simple but very powerful. With a few built-in functions, you can create files, read content, write logs, append data, and safely manage files on the server.
For most applications:
- Use
file_get_contents()for quick file reading - Use
file_put_contents()for simple writing tasks - Use
fopen()andfwrite()when you need more control - Always validate paths and handle errors properly
Once you understand the basics, PHP file handling becomes useful in logging systems, configuration management, caching, report generation, and many real-world backend tasks.
Download Source Code
Download the complete PHP file handling demo project used in this tutorial.
Download the PHP File Handling Demo Project
The downloadable project includes:
- File read and write examples
- Append and delete operations
- Simple clean UI
- Setup instructions
- Ready-to-run PHP files
PHP File Handling Functions Cheat Sheet
The following table summarizes the most commonly used PHP file handling functions.
| Function | Purpose |
|---|---|
fopen() |
Open a file |
fclose() |
Close an opened file |
fwrite() |
Write data into a file |
fgets() |
Read a single line from a file |
fread() |
Read a specified number of bytes |
file_get_contents() |
Read complete file content |
file_put_contents() |
Write content into a file |
file_exists() |
Check whether a file exists |
unlink() |
Delete a file |
filesize() |
Get file size |
rename() |
Rename a file |
copy() |
Copy a file |
The best tutorial to read about file options in PHP. Thanks.
Welcome Rithiga.
Hi Vincy,
Thanks for posting all of your articles – a lot of them have been very helpful to me. However, I’m struggling to implement a multi-directory website that uses “include()” or “require()” from different directories to several different directories in my structure. I’ve tried to set a $ROOT variable but keep getting the error “failed to open stream : No such file or directory in C:\intepub\wwwroot\path\to\file\fileName.php” when the file exists in the named directory. Could you write a blog about how to include php files from anywhere in your code using the $ROOT (global?) variable.
I’m sure lots of newbie programmers out there would appreciate it, too.
Thanks in advance,
Dave.
Hi Dave,
Check this tutorial https://phppot.com/php/comparison-between-include-and-require-statements-in-php/