Sort by date an array of files

3

I have a small PHP script to view the folder files on the server, but first I need to sort the files by the most recent and I do not know where to place the asort in the code below:

if($folder) {
   if(strstr($folder,'..')) exit(ERROR_MESAGE);
       $dir = @opendir('./'.$folder);
   } else {
       $dir = @opendir('./');
   } 

   while($file = @readdir($dir)) {
      if($file != '.' && $file != 'Índex.php' && $file != '.htaccess' && $file != 'css' &&$file !='.nomedia') {
          if($con < $n) {
             $con++; 
             continue;
          }

   if($sok < FILES_ON_PAGE) {
       $name = $file;
       $er = strrchr($name,'.');
       if(file_exists($folder.'/in.html')) 
           require_once($folder.'/in.html');
       if(file_exists($folder.'/1.txt')) 
           require_once($folder.'/1.txt');
       if($folder) {
           $sz = filesize($folder.'/'.$file);
           $file = $folder.'/'.$file;
       }   else  {
           $sz = filesize($file);
       }
       $fsize = round($sz/1024,1);

       if(is_file($file))           
       { '

I need to pass a asort() in the files and I can not find a way to get it, how can I do it?

    
asked by Bryan B Weiss 23.01.2016 в 03:38
source

3 answers

4

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;
             }
    
             ....
    
        
    answered by 23.01.2016 / 06:13
    source
    1

    You could do something like this:

    <?php
    //Directorio a listar
    $path = './pdf';
    //Abre un enlace al directorio
    $dir = opendir($path);
    //Iteramos el directorio
    while($file=readdir($dir)){
        if(!is_dir($file)){
            //Guardamos en un array el archivo y la fecha del mismo
            $data[] = array($file, date("Y-m-d H:i:s",filemtime($path.'/'.$file)));
            //obtenemos las fechas de cada archivo, que sirven para ordenar el array anterior con la funcion array_multisort
            $dates[] = date("Y-m-d H:i:s",filemtime($path.'/'.$file));
        }
    }
    //cerramos el enlace al directorio
    closedir($dir);
    //ordenamos el array data según las fechas almacenadas en $dates
    array_multisort($dates, SORT_DESC, $data);
    
    //Mostramos el resultado despues de ordenar
    echo "<pre>";
    echo "Arreglo de fechas para ordenar";
    echo "<br/>";
    print_r($dates);
    
    echo "Archivos ordenados";
    echo "<br/>";
    print_r($data);
    echo "</pre>";
    ?>
    
        
    answered by 23.01.2016 в 06:10
    0

    I would get the files with the function glob() this function saves the files in a array even saves the size and the last date of modification of each one, and being in a array you could do the asort() whether by date, size or name.

        
    answered by 03.09.2016 в 16:07