Sort and Display Directory List Alphabetically Using Opendir() in PHP

Sort and display directory list alphabetically using opendir() in php

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.

Sort opendir In Alphabetical Order

I would use scandir() instead:

$user = $fgmembersite->UserFullName();
$files = scandir('users/' . $user . '/');
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
// Do stuff here
}
}

As Blauesocke pointed out, it is already sorted.

PHP opendir Sort files

I cannot tell why you get different results (different filesystems lead to different results?)...

To sort the list, however, the only option is to create an intermediate array that holds all the files:

$dir = "../DB";
$allfiles = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
$allfiles[] = $file;
}
closedir($dh);
}
}
sort($allfiles);
foreach($allfiles as $file) {
echo "filename:" . $file . "<br>";
}

EDIT:

This version is recursive:

function printFoldersRecursive($dir)
{
$allfiles = array();

// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '.' && $file != '..') {
$allfiles[] = $file;
}
}
closedir($dh);
}
}

sort($allfiles);

foreach($allfiles as $file) {
echo "filename:" . $dir.'/'.$file . "<br>\n";
if(is_dir($dir.'/'.$file)){
printFoldersRecursive($dir.'/'.$file);
}
}
}

printFoldersRecursive('../DB');

How can I list all files in a directory sorted alphabetically using PHP?

The manual clearly says that:

readdir

Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

What you can do is store the files in an array, sort it and then print it's contents as:

$files = array();
$dir = opendir('.'); // open the cwd..also do an err check.
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..") and ($file != "index.php")) {
$files[] = $file; // put in array.
}
}

natsort($files); // sort.

// print.
foreach($files as $file) {
echo("<a href='$file'>$file</a> <br />\n");
}

Sort alphabetically with opendir()

What's wrong with the arrays?
Also it would be better if you use pathinfo to obtain the filename and the extension.

$max_width = 100;
$max_height = 100;
$imagedir = 'gifs/animals/'; //Remember trailing slash


function getPictureType($ext) {
if ( preg_match('/jpg|jpeg/i', $ext) ) {
return 'jpg';
} else if ( preg_match('/png/i', $ext) ) {
return 'png';
} else if ( preg_match('/gif/i', $ext) ) {
return 'gif';
} else {
return '';
}
}

function getPictures() {
global $max_width, $max_height, $imagedir;
if ( $files = scandir($imagedir) ) {
$lightbox = rand();
echo '<ul id="pictures">';
foreach ($files as $file) {
$full_path = $imagedir.'/'.$file;
if ( !is_dir($file) ) {
$finfo = pathinfo($full_path);
$ext = $finfo['extension'];
if ( ($type = getPictureType($ext)) == '' ) {
continue;
}

$name = $finfo['filename'];
$title = str_replace("_"," ",$name);
echo '<li><a href="'.$name.'">';
echo '<img src="thumbs/'.$file.'" class="pictures" alt="'.$file.'" />';
echo '</a>';
echo ''.$title.'';
echo '</li>';
}
}
echo '</ul>';

}
}

How does PHP readdir/opendir sort


The entries are returned in the order in which they are stored by the filesystem.

http://php.net/manual/en/function.readdir.php

PHP (folder) File Listing in Alphabetical Order?

Instead of using readdir you could simply use scandir (documentation) which sorts alphabetically by default.

The return value of scandir is an array instead of a string, so your code would have to be adjusted slightly, to iterate over the array instead of checking for the final null return value. Also, scandir takes a string with the directory path instead of a file handle as input, the new version would look something like this:

foreach(scandir($mainframe->getCfg( 'absolute_path' ) ."/images/store/") as $file) {
// rest of the loop could remain unchanged
}

Displaying opendir results in a select list alphabetically

An easy way is to use scandir. You can specify a sort order using SCANDIR_SORT_ASCENDING (0) or SCANDIR_SORT_DESCENDING (1):

$files2 = scandir(WAVEFORM_RELATIVE_PATH, SCANDIR_SORT_ASCENDING);
foreach($files2 as $file) {
if (in_array(substr(strtolower($file), -4), array('.png'))) {
echo '<option'.($TRACKS->waveform==$file? ' selected="selected"' : '').'>'.$file.'</option>'."\n";
}
}


Related Topics



Leave a reply



Submit