how do i modify the way in which readdir() lists files.
I have a script that creates a zip
package daily in a directory. After this is done another script deletes the 'last' file in the directory so I always have just the latest x days.
whil开发者_Python百科e (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
echo "$file";
echo '<br>';
//count files
$file_count = $file_count + 1;
}
}
However suddenly readdir()
is returning the list of files like this:
March_16_2011.zip
March_12_2011.zip
March_13_2011.zip
March_14_2011.zip
March_15_2011.zip
So of course rather than the oldest file being removed the newest one is.
When I look at the files in FTP they are all dated correctly.
Why is readdir()
returning them out of order in this case? How do I force it to order them in a way I want? (By date)
readdir
returns the filenames in an arbitrary order, depending on how the OS returns the entries from the filesystem. You need to manually sort the result list:
foreach (glob("*") as $fn) {
$files[$fn] = filemtime($fn);
}
arsort($files);
$files = array_keys($files);
AFAIK there is no PHP function to sort by date, but you can write your own:
$filearr = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$stat = stat($file);
$filearr["$file"] = $stat['mtime'];
}
}
asort($filearr);
Also see: http://nl2.php.net/manual/en/function.stat.php
foreach (glob("$dir/*.zip") as $f) echo $f;
that's all code you need if give your files sensible names, like 2011-03-12.zip
.
You can not force readdir() to order the files. But you can check which is the oldest file with stat().
Try using scandir instead of readdir to set a sorting for your files
More info on scandir: http://uk3.php.net/manual/en/function.scandir.php
Otherwise you could read your folderstructur into an array and sort it afterwards using the various php sorting functions.
I would use glob()
. That sorts them automatically, via number as well, and might be better to get the files, too...
glob("data/*.{zip,tar.gz,tar.bz2}", GLOB_BRACE);
But to sort via the date, you may have to do something like this:
$data = $FILE_NAME_VAR_HERE; // duh
$parts = explode("_"); // explode it by underscore
unset($parts[0]); // unset the first one
$data = implode("_", $parts); // return the string without it
Untested.
Hope this fixes your problem :)
Ol' faithful array_multisort()
could also be drafted in to work with the list of files from glob()
.
$files = glob("*.zip");
$times = array_map('filemtime', $files);
array_multisort($times, $files);
精彩评论