In this third part of an eight-part article series on using PHP to work with the file and operating system, you'll learn how to retrieve the size of a directory and find out a file's last access and modification times. This article is excerpted from chapter 10 of the book Beginning PHP and PostgreSQL 8: From Novice to Professional, written by W. Jason Gilmore and Robert H. Treat (Apress; ISBN: 1590595475).
PHP doesn't currently offer a standard function for retrieving the total size of a directory, a task more often required than retrieving total disk space (see disk_total_space()). And although you could make a system-level call to du using exec() or system() (both of which are introduced later in this chapter), such functions are often disabled for security reasons. The alternative solution is to write a custom PHP function that is capable of carrying out this task. A recursive function seems particularly well-suited for this task. One possible variation is offered in Listing 10-2.
Note The du command will summarize disk usage of a file or directory. See the appropriate man page for usage information.
Listing 10-2. Determining the Size of a Directory's Contents
<?php function directory_size($directory) { $directorySize=0;
/* Open the directory and read its contents. */ if ($dh = @opendir($directory)) {
/* Iterate through each directory entry. */ while (($filename = readdir ($dh))) {
/* Filter out some of the unwanted directory entries. */ if ($filename != "." && $filename != "..") {
// File, so determine size and add to total. if (is_file($directory."/".$filename)) $directorySize += filesize($directory."/".$filename);
// New directory, so initiate recursion. */ if (is_dir($directory."/".$filename)) $directorySize += directory_size($directory."/".$filename); } } #endWHILE } #endIF