How to work with files/folders in PHP
By Flavio Copes
Learn how to work with files in PHP using file_exists and filesize, open them with fopen, read with fgets, write with fwrite, and delete with unlink.
PHP gives you filesystem access out of the box: you check files with file_exists(), read them with fopen() and fgets() (or file_get_contents()), write with fwrite(), delete with unlink(), and manage folders with mkdir() and scandir().
PHP is a server-side language, so unlike JavaScript in the browser it can freely touch the disk. Reading a config file, saving an upload, writing a log: it’s all a function call away.
Checking and inspecting files
You can check if a file exists using file_exists():
file_exists('test.txt') //true
Get the size of a file in bytes using filesize():
filesize('test.txt')
Reading files
You can open a file using fopen(). Here we open the test.txt file in read-only mode and we get what we call a file descriptor in $file:
$file = fopen('test.txt', 'r');
We can terminate the file access calling fclose($file).
Read the content of a file into a variable:
$file = fopen('test.txt', 'r');
$data = fread($file, filesize('test.txt'));
You can also read a file line by line using fgets():
$file = fopen('test.txt', 'r');
while (!feof($file)) {
$line = fgets($file);
//do something
}
feof()checks that we haven’t reached the end of the file yet.
For simple cases there’s a shortcut. file_get_contents() reads the whole file into a string in one call:
$data = file_get_contents('test.txt');
I reach for this most of the time. The fopen() route is better for big files, because you process them a chunk at a time instead of loading everything in memory.
Writing files
To write to a file you must first open it in write mode, then use fwrite():
$data = 'test';
$file = fopen('test.txt', 'w');
fwrite($file, $data);
fclose($file);
Be careful with the 'w' mode: it truncates the file to zero length as soon as you open it. If the file had content, it’s gone. To add to the end of an existing file, open it in append mode with 'a' instead.
The shortcut version here is file_put_contents():
file_put_contents('test.txt', 'test');
We can delete a file using unlink():
unlink('test.txt');
Working with folders
Check if a path is a folder with is_dir(), and create one with mkdir():
mkdir('uploads');
List the content of a folder with scandir(), which returns an array of names:
scandir('uploads')
//['.', '..', 'avatar.jpg', 'report.pdf']
Notice the . and .. entries, the current and parent folder. You usually filter them out.
Delete an empty folder with rmdir():
rmdir('uploads');
Those are the basics, of course there are more functions to work with files.