According to the documentation , when using readdir
the files are returned in the same order in the that are in the system (which could be anything from the creation date to the alphabetical order) and that order can not be controlled a priori.
One option would be to create an array with the information you need from the files (at least the name that is used in the code above, plus the date that will be used for the sorting), then order that array and operate with it instead of directly with the result of readdir
.
For this you would need:
-
Declare a class for the files, for example:
class MiArchivo {
public $nombre = "";
public $fecha = 0;
function __construct($nombre, $fecha) {
$this->nombre = $nombre;
$this->fecha = $fecha;
}
}
-
Create an empty array where the files will be placed:
$misarchivos = array();
-
Create a comparison function that will be used with usort
to sort the array of objects:
function comparaMiArchivo($a, $b) {
return $a->fecha < $b->fecha;
}
With that in mind, the steps to follow would be the following:
Define the class (ex: MiArchivo
)
Defines the comparison function (ex: comparaMiArchivo()
)
Declares the array that will contain the information of the files (ex: $misarchivos
)
While there are files using readdir
Read the file and its modification date (using filemtime
)
Create an object of class MiArchivo
Insert it into the array declared in step 3
Sort the array using usort
and the comparison function defined in step 2
Go through the array applying the same code you had, only now instead of $file
you would need something like $misarchivos[x]->nombre
.
The code would be something like this:
class MiArchivo {
public $nombre = "";
public $fecha = 0;
function __construct($nombre, $fecha) {
$this->nombre = $nombre;
$this->fecha = $fecha;
}
}
function comparaMiArchivo($a, $b) {
return $a->fecha < $b->fecha;
}
$misarchivos = array();
if($folder) {
if(strstr($folder,'..')) exit(ERROR_MESAGE);
$dir = @opendir('./'.$folder);
} else {
$dir = @opendir('./');
}
while($file = @readdir($dir)) {
array_push($misarchivos, new MiArchivo($file, filemtime($folder ."./" . $file)));
}
usort($misarchivos, "comparaMiArchivo");
// a partir de aquí el array de archivos está ordenado de más reciente a más antiguo
foreach($misarchivos as $file) {
// el mismo código que tenías, pero en lugar de $file sería $file->nombre
if($file->nombre != '.' && $file->nombre != 'Índex.php' && $file->nombre != '.htaccess' && $file->nombre != 'css' &&$file->nombre !='.nomedia') {
if($con < $n) {
$con++;
continue;
}
....