Jump to content

Display Images alphabeticlly from a directory


AndrewFerrara

Recommended Posts

I am trying to display images on a html page alphabetically in descending order by their filename.

 

This script inserts all the images in a directory on the page. Just can't figure out how to maintain this with a sorting option

 

<?php

$dir = "./plate_cache";
$handle = opendir($dir);
while (($file = readdir($handle))!==false)
{
	if (strpos($file, '.png',1)) 
	{
	echo "<img id=\"plates\" src=\"/tags/plate_cache/$file\"></a><br />;";
	}
}
closedir($handle); 
}

?>

You have multiple options (I won't list them all).

 

1. Use glob() which sorts the files in ascending alphabetical order, then reverse the array.

 

2. Use scandir() which also sorts the files in ascending alphabetical order, but does not allow filtering which files are returned (you want only PNG images). Then filter the array to get PNGs, then sort it.

 

3. Continue using readdir, but create an array of the PNG images instead of echoing. Then sort the array. Then echo each image.

 

Which route do you think you'd like to follow?

This is what i found in php.net

<?php
function mi_dir_list($a_path=".", $a_mask="*")
{
    $dir = @ dir("$a_path");

    //List files in images directory
    while (($file = $dir->read()) !== false)
    {
       if($file !="." && $file!=".." && fnmatch($a_mask, $file))
         $l_vdir[] = $file;
    }

    $dir->close();

    return($l_vdir);
}

$lv = mi_dir_list( "../pruebas/", "*.*");
print_r($lv);
?>

Here's what u will do

 

	if ( $handle = opendir($path) ) {
	$files = array();
	while ( ($file = readdir($handle)) !== false ) {
		$files[] = $file;
	}
	sort($files);
	foreach ( $files as $file ) {
		// Do stuff here
	}
}

 

if u use image names with numbers it would be better to set

	if ( $handle = opendir($path) ) {
	$files = array();
	while ( ($file = readdir($handle)) !== false ) {
		$files[] = $file;
	}
	NATCASESORT($files); //This is what i've changed
	foreach ( $files as $file ) {
		// Do stuff here
	}
}

Cuz like this it will list for ex. 1img.jpg, 2img.jpg, 11img.jpg otherwise it would to 1img.jpg, 11img.jpg, 2img.jpg. If u dont understand any line in code feel free to ask me

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.