Forum Moderators: coopster
I could use help with a small script. Problem: Some of the files are listed out of numerical order (2,3,1,4,5). Here is the set-up:
One directory with 12 subdirectories, one for each month. Each subdirectory has a subdirectory for each week of that month. Each week's directory has an index.html file.
The script is a basic file lister. The code is placed 12 times in an index.php file to create a sitemap for the main directory. This is one section (of the 12):
echo "<dl><dt><b>Jan 2003</b></dt><dd><table border='0'><tr>";
$jandir="jan2003/";
$jan=opendir($jandir);
while($janb=readdir($jan))
{
$janc = $janb;
$janb = str_replace(".","",$janb);
$janb = str_replace("..","",$janb);
$janb = str_replace("week"," Week ",$janb);
echo "<td><a href=$jandir$janc>$janb</a></td>";
}
closedir($jan);
echo "</tr></table></dd></dl>"; Any particular fixes for this? Also, I've yet to figure out why 'dots' are listed as files if I remove the string replace lines.
TIA :)
1. Files are only listed in order when you do a file listing because you apply a sort to the listing after the listing is generated. Alphabetical by filename is only one possible sort. The file system doesn't care at all about what order the file names are in. So you need to get the names and then apply the order.
2. On a *.nix system, there is no real differentiation between a file and a directory. A directory is merely a file that holds information about files. Two pieces of that info are 1) current dir and 2) parent dir and they will be part of the file table and considered valid files (since, well, they are valid files). I don't know how this works on windows, but it may be the same. I just checked and it seems to be the same. When you do a directory listing in Win it gives you the . and the.. so I guess it's generally true.
Tom
// Load up an array with the directory listing:
$dir = 'jan2003/';
if ($handle = @opendir($dir)) {
while (false!== ($filename = readdir($handle))) {
$files[] = $filename;
}
closedir($handle);
natcasesort($files);
// Process the files from the directory listing;
// but skip any files beginning with dots (.):
foreach ($files as $filename) {
if (is_file($dir.$filename) and substr($filename, 0 , 1)!= '.') {
// your statements here...
}
}
}
<edit>cleaned up formatting of lines</edit>
[edited by: coopster at 12:01 am (utc) on Dec. 8, 2003]
Hmm, interesting. I tested this on both freeBSD and Linux servers (Apache 1.3/PHP 4.2.3) and if I print out the $files array, I can see the . and .. files in the array -- however, evaluating it during the loop always eliminates them for me (as well as any .htaccess files or otherwise). What type of configuration are you running?