Sort by upload date after a readdir

1

I have this code that works fine, but I would like the last images to be uploaded to appear at the top of the page instead of appearing in a seemingly random order '.

They are not in a database, they are only in a folder where they use the move_uploaded_file(pics/....) function.

$myDirectory = opendir("pics");
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

closedir($myDirectory);

$indexCount = count($dirArray);

for($index=0; $index < $indexCount; $index++) {
    $temp = explode('.', $dirArray[$index]);
    $extension = strtolower(end($temp));
    if ($extension == 'jpg' || $extension == 'png' || $extension == 'tif' || $extension == 'gif' || $extension == 'jpeg' || $extension == 'JPG'){ 
        echo '<a href="pics/' . $dirArray[$index] . '"><img class="image" src="pics/' . $dirArray[$index] . '" alt="Image"></a>';
    }
}
    
asked by anonymous 28.05.2014 / 18:41

2 answers

0

With arsort , a dateint was created with the value generated by filemtime and with it the arsort simply sort the array that was created ( $img ), the largest date being first.

<?php        
     $path = "pics/";
     $dir  = opendir($path);
     $img  = array();
     $exts = array('jpg', 'png', 'tif','gif'); //extensões aceitas
     if ($dir){
         while($arq = readdir($dir)){
             $ins = explode('.', $arq);
             $out = strtolower(end($ins));
             if ($arq != '.' && $arq != '..' && in_array($out, $exts)){
                $dateint = filemtime($path.$arq); 
                array_push($img, array(
                                 'dateint' => $dateint,
                                 'name' => $arq, 
                                 'date' => date('d/m/Y H:m:s', $dateint)));
             }
         }
         if ($img && sizeof($img) > 0){
             arsort($img);       
             foreach($img as $value){                
                 echo '<p>';
                 echo '<a href="pics/'.$value['name'].'">';
                 echo '<img class="image" src="pics/'.$value['name'].'" alt="Image">';
                 echo '</a>';
                 echo '</p>';
             }
         }
     }
    
29.05.2014 / 16:27
2

You can use the filemtime() function to know the recording date of each image. Which can be used as a key to sort images using uksort() , before being processed .

See also:

Example:

<?php
    function mtimecmp($a, $b) 
    {
        $mt_a = filemtime($a);
        $mt_b = filemtime($b);

        if ($mt_a == $mt_b)
            return 0;
        else if ($mt_a < $mt_b)
            return -1;
        else
            return 1;
    }

    $imagens = glob($myDirectory."*.jpg");
    usort($imagens, "mtimecmp");
    array_reverse($imagens);

    foreach ($imagens as $imagem) 
    {
        echo '<img src="'.$imagem.'" height ="400"/><br>';
    }
?>

Source SOEN

    
29.05.2014 / 11:49