Click to See Complete Forum and Search --> : iterating through the filesystem
HELP !
i need to build a database wich keeps track of all the files and directories on a certain (web)share.
for instance:
i have a virtual directory named /files
now i want to use php to iterate through all the files and directories under that virtual folders.
I know how to do in ASP (bleeeh !), but now i want to implementate it using PHP4.
Can someone help ?
Just adding myself to this thread as I am very interested in replies to this question.
matt.
There are a bunch of nice little file and directory functions in PHP4 that will help you do this, let me dig up the manual references for you. I wrote a small one (poorly hacked together and only to one subdir level) to build some mp3 playlists for streaming files.
Take a look in the PHP manual in the following sections (there are tiny examples in each also)
XII. Directory functions
XVI. Filesystem functions
I'm sure you will spot the correct functions easily and with some looping and logic it should be no problem.
Hope that gives you a good start.
One simple way to do it is with recursion.
(This is pseudocode, btw, I don't know the exact function names, etc)
function doDir($dir) {
$dirEntries = dirlisting($dir);
foreach ($dirEntries as $entry) {
if $entry is file {
do your thing...
}
else if $entry is dir {
doDir($entry);
}
}
}
It's not beautiful, it will probably die a horrible death if you have too many subdirs (on the order of a few hundred would be my guess... just a guess...), and there is much more you can do there, but it should work.
Here's some useful code all put together in a class.
This class could be easily extended to return other info about a directory as well. Please send back a copy if you do so.
Usage shown below.
matt.
<?PHP
class DirectoryInfo
{
//recursively gets the size of a directory.
function get_dir_size($dir, &$size)
{
$handle = opendir($dir);
while( $file = readdir($handle) )
{
if($file != '.' and $file != '..')
{
is_dir("$dir/$file") ? $this->get_dir_size("$dir/$file", $size) : $size += filesize("$dir/$file");
}
}
return $this->display_size($size);
}
// File size calculations - for display.
function display_size($file_size)
{
if($file_size >= 1073741824)
{
$file_size = round($file_size / 1073741824 * 100) / 100 . " Gb";
}
elseif($file_size >= 1048576)
{
$file_size = round($file_size / 1048576 * 100) / 100 . " Mb";
}
elseif($file_size >= 1024)
{
$file_size = round($file_size / 1024 * 100) / 100 . " Kb";
}
else
{
$file_size = $file_size . " bytes";
}
return $file_size;
}
}
$d = new DirectoryInfo;
echo "<P>" . $d->get_dir_size("C:/Inetpub", $size);
?>
I don't know exatly what you need, but a completly different approch is to execute a shell-command like 'dir /s > files.txt'
and the read the file files.txt.
There're severel switches to use with the dir-command, e.g. checking for attributes.
PHP Builder
Copyright WebMediaBrands Inc. All Rights Reserved.