18

php noob here - I've cobbled together this script to display a list of images from a folder with opendir, but I can't work out how (or where) to sort the array alphabetically

<?php

// opens images folder
if ($handle = opendir('Images')) {
while (false !== ($file = readdir($handle))) {

// strips files extensions  
$crap   = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-");    

$newstring = str_replace($crap, " ", $file );   

//asort($file, SORT_NUMERIC); - doesnt work :(

// hides folders, writes out ul of images and thumbnails from two folders

    if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") {
    echo "<li><a href=\"Images/$file\" class=\"thickbox\" rel=\"gallery\" title=\"$newstring\"><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\"  </a></li>\n";}
}
closedir($handle);
}

?>

Any advice or pointers would be much appreciated!

felixthehat
  • 849
  • 2
  • 9
  • 24

5 Answers5

23

You need to read your files into an array first before you can sort them. How about this?

<?php
$dirFiles = array();
// opens images folder
if ($handle = opendir('Images')) {
    while (false !== ($file = readdir($handle))) {

        // strips files extensions      
        $crap   = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-");    

        $newstring = str_replace($crap, " ", $file );   

        //asort($file, SORT_NUMERIC); - doesnt work :(

        // hides folders, writes out ul of images and thumbnails from two folders

        if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") {
            $dirFiles[] = $file;
        }
    }
    closedir($handle);
}

sort($dirFiles);
foreach($dirFiles as $file)
{
    echo "<li><a href=\"Images/$file\" class=\"thickbox\" rel=\"gallery\" title=\"$newstring\"><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\"  </a></li>\n";
}

?>

Edit: This isn't related to what you're asking, but you could get a more generic handling of file extensions with the pathinfo() function too. You wouldn't need a hard-coded array of extensions then, you could remove any extension.

zombat
  • 92,731
  • 24
  • 156
  • 164
  • I came across this post because while I had the same code asort() would not work and I could not figure out why and I still don't know why but I see from the comment in here that zombat had the same problem. Thanks for leaving the comment in there it was a big help... – user1946891 Nov 27 '19 at 21:38
12

Using opendir()

opendir() does not allow the list to be sorted. You'll have to perform the sorting manually. For this, add all the filenames to an array first and sort them with sort():

$path = "/path/to/file";

if ($handle = opendir($path)) {
    $files = array();
    while ($files[] = readdir($dir));
    sort($files);
    closedir($handle);
}

And then list them using foreach:

$blacklist = array('.','..','somedir','somefile.php');

foreach ($files as $file) {
    if (!in_array($file, $blacklist)) {
        echo "<li>$file</a>\n <ul class=\"sub\">";
    }
}

Using scandir()

This is a lot easier with scandir(). It performs the sorting for you by default. The same functionality can be achieved with the following code:

$path = "/path/to/file";
$blacklist = array('somedir','somefile.php');

// get everything except hidden files
$files = preg_grep('/^([^.])/', scandir($path)); 

foreach ($files as $file) {
    if (!in_array($file, $blacklist)) {
        echo "<li>$file</a>\n <ul class=\"sub\">";
    }
}

Using DirectoryIterator (preferred)

$path = "/path/to/file";
$blacklist = array('somedir','somefile.php');

foreach (new DirectoryIterator($path) as $fileInfo) {
    if($fileInfo->isDot()) continue;
    $file =  $path.$fileInfo->getFilename();
    echo "<li>$file</a>\n <ul class=\"sub\">";
}
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
3

This is the way I would do it

if(!($dp = opendir($def_dir))) die ("Cannot open Directory.");
while($file = readdir($dp))
{
    if($file != '.')
    {
        $uts=filemtime($file).md5($file);  
        $fole_array[$uts] .= $file;
    }
}
closedir($dp);
krsort($fole_array);

foreach ($fole_array as $key => $dir_name) {
  #echo "Key: $key; Value: $dir_name<br />\n";
}
HpTerm
  • 8,151
  • 12
  • 51
  • 67
namit
  • 113
  • 3
  • 8
1
$directory = scandir('Images');
Emil
  • 7,220
  • 17
  • 76
  • 135
1

Note: Move this into the foreach loop so that the newstring variable gets renamed correctly.

// strips files extensions      
$crap   = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-");    

$newstring = str_replace($crap, " ", $file );
HpTerm
  • 8,151
  • 12
  • 51
  • 67
Jason
  • 11
  • 1