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 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025