Skip to content

How to work with files/folders in PHP

New Course Coming Soon:

Get Really Good at Git

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 as fgets 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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my PHP Handbook

Here is how can I help you: