11Jun 2007
A Use For PHP 5's Directory Iterator
Hey, peoples! If you're a retarded stat monkey like I am you'll appreciate this one. I threw together a script that spiders an entire given directory and returns how many lines of code, bytes, files and sub directories there are. One of those strange curiosities I had, I s'pose. Anyhow, you're free to play with it. I tend to write useless bits of code that amuse me with equally useless statistics.
You will need PHP 5.1 or newer to use this function as it utilizes some objects found only in the 5.x builds.
These are the results I get when I run this function on the latest build of MyTopix:
MyTopix Stats: ( for php and css files )
----------------------------------------
30 Directories
109 Files
58,372 Lines
2,524,811 Bytes
To use this function just copy and paste the following block of code in a php file or, alternatively, just download the package in the link I provided at the end of this entry.
<?php
/**
* A recursive directory iterator that spiders and generates meta
* data for a given path. Will return information only for files
* whose extensions match the ones specified within the $filter
* parameter.
*
* This version ignores subversion directories (.svn), but can be
* modified to include others.
*
* WORKS IN PHP 5.1 AND UP!!!
*
* Usage:
* ==============================================================
*
* $meta = metaSpider('/path/to/project/');
*
* echo "<strong>Bytes:</strong> {$meta['bytes']}<br />";
* echo "<strong>Files:</strong> {$meta['files']}<br />";
* echo "<strong>Lines:</strong> {$meta['lines']}<br />";
* echo "<strong>Directories:</strong> {$meta['directories']}";
*
* @param $directory The directory to spider
* @param $filter Extensions of files to search
* @return Array
*/
function metaSpider($directory, $filter = array('php', 'xsl', 'xml', 'tpl', 'css'))
{
$count_directories = 0;
$count_files = 0;
$count_lines = 0;
$count_bytes = 0;
$iterator = new RecursiveDirectoryIterator($directory);
foreach(new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file)
{
if(false == $file->isDir())
{
if(in_array(end(explode('.', $file->getFileName())), $filter))
{
$count_files++;
$count_bytes += $file->getSize();
$count_lines += sizeof(explode("n", file_get_contents($file->getPathName())));
}
}
else if(false == strpos($file->getPathname(), '.svn') && $file->isDir())
{
$count_directories++;
}
}
return array('bytes' => $count_bytes,
'files' => $count_files,
'lines' => $count_lines,
'directories' => $count_directories);
}
?>
For those of you who have seen this entry before, yes, I just went ahead and copied it from the support boards. Thought that this place was as good as any to keep all my php stuff.
Besides, more people will be able to make use of it this way.