How to work with files/folders in PHP
PHP is a server-side language and one of the handy things it provides is access to the filesystem.
You can check if a file exists using file_exists()
:
file_exists('test.txt') //true
Get the size of a file using filesize()
:
filesize('test.txt')
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($fd)
.
Read the content of a file into a variable:
$file = fopen('test.txt', 'r')
fread($file, filesize('test.txt'));
//or
while (!feof($file)) {
$data .= fgets($file, 5000);
}
feof()
checks that we haven’t reached the end of the file asfgets
reads 5000 bytes at a time
You can also read a file line by line using fgets()
:
$file = fopen('test.txt', 'r')
while(!feof($file)) {
$line = fgets($file);
//do something
}
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);
We can delete a file using unlink()
:
unlink('test.txt')
Those are the basics, of course there are more functions to work with files.
I wrote 21 books to help you become a better developer:
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- Svelte Handbook
- CSS Handbook
- Node.js Handbook
- Vue Handbook