What function would I use to read the name of all files and their sizes in a certain directory and output that onto a page?
| SitePoint Sponsor |
What function would I use to read the name of all files and their sizes in a certain directory and output that onto a page?




PHP Code:<?php
if ($handle = opendir('/path/to/files')) {
echo "Files:";
echo "<table>";
while (false !== ($file = readdir($handle))) {
printf("<tr><td>%s</td><td>%s</td></tr>", $file, filesize($file));
}
echo "</table>";
closedir($handle);
}
?>
First I got an accessd denied but a chmod edit fixed that.
Here's are the results though. Not exactly what I want.
Plus I don't want this to list files such as htaccess.PHP Code:Warning: stat failed for site_db_backup.sql (errno=2 - No such file or directory) in /home/cgshock/public_html/admincp/backup.php on line 20
site_db_backup.sql
.htaccess 69
Warning: stat failed for boards_db_backup.sql (errno=2 - No such file or directory) in /home/cgshock/public_html/admincp/backup.php on line 20
boards_db_backup.sql
. 4096
.. 4096
site_db_backup.sql
.htaccess 69
boards_db_backup.sql




Oops... had one small mistake... ;-)
PHP Code:<?php
$path = '/path/to/files';
if($dir = opendir($path)) {
echo "Files in $path:";
echo "<table>";
while (false !== ($file = readdir($dir))) {
printf("<tr><td>%s</td><td>%s</td></tr>", $file, filesize("$path/$file"));
}
echo "</table>";
closedir($dir);
}
?>
Works great, but only one thing. How would I take out the ".", "..", and any files that begin with a dot (such as htaccess) from the results?
Since I'm planning to store files of only one type in a dir perhaps do some sort of a filter to only display .SQLs?
Also how can I change the file size to be displayed in kbs instead of bytes?
Last edited by Codename49; Jun 25, 2002 at 10:37.





the lineCode:<?php $path = '/path/to/files'; if($dir = opendir($path)) { echo "Files in $path:"; echo "<table>"; while ($file = readdir($dir)) { if (!preg_match('/\.\.?$/', $file)) printf("<tr><td>%s</td><td>%s</td></tr>", $file, filesize("$path/$file")); } echo "</table>"; closedir($dir); } ?>
if (!preg_match('/\.\.?$/', $file))
ignores the "." and ".." entry.
if you want to list just those files with a specific extension use this line instead of the if (!...)
You can list other extension inside the brackets, just separate them with a pipe "|".Code:if (preg_match('/\.(sql|php|inc)$/i', $file))
Bookmarks