Useful PHP Functions for Dealing with the File System

Undoubtedly at some point when working with PHP you’ll wind up needing to access or manipulate the file system. PHP has plenty of file system related functions built right into the core for you to sink your teeth into, however you will often need to use a combination of them to carry out more slightly advanced tasks.

Here are a few functions I regularly use during my day to day meddling in PHP.

Delete a File/Recursively Delete a Directory

This function simply deletes a directory and all of its contents, it can also delete a single file.

Note: Be very careful with the path you pass to this!

Copy a File/Recursively Copy the Contents of a Directory

Have you ever needed to copy the contents of one directory to another? That’s exactly what the following function will do.

Get the Size of a File/Directory

Sometimes you need to calculate the size of a file or directory, PHP has filesize() for files but lacks a function to do the same for directories. This function can do both!

Note: This function may return unexpected results for files larger than 2GB on 32bit hosts due to PHP’s integer type being 32bit signed.

Read the Last Few Lines of a File (aka tail for PHP)

I can recall a handful of times that I have had to read the last few lines of a large log file with PHP without loading the whole file into memory. Obviously I could just do tail -n <number of lines> <file> on Unix-like systems, but what if your code is running on Windows?

That’s where this function jumps to the rescue.

NOTE: Only works with files that have CRLF, LF or CR newlines.

I hope you find these functions as useful as I do.