0

Hi,

I am trying to make a simple php photo gallery, I have this code, but the only problem is that the photos appear in a random order.

How can I get the photos to appear alphabetically or numerically?

<?php
if ($handle = opendir('photos/')) {
   while (false !== ($file = readdir($handle)))
      {
          if ($file != "." && $file != "..")
	  {     
          	

		$photos .= '	
				<img src="thumbs.php?src='.$file.'&f=2&t=3" alt="'.$file.'" title="'.$file.'"/>
				';
          }
       }
  closedir($handle);
  }
?>
<?php print $photos; ?>

Thank you

4
Contributors
7
Replies
8
Views
6 Years
Discussion Span
Last Post by 84hd0ns
0

Use scandir() instead of the readdir() to get the files to an array. Scandir() also has the capability of pulling the files in either ascending or descending order array scandir ( string $directory [, int $sorting_order = 0 ] ) Once you get the array, you can use the same while loop to loop through the array to display the images.

0

Usually what i do is, when i upload a photo i store the filename (eg picture.jpg), and some other details about the picture in a table (eg tblPictures). In this table i also have an extra column "order_id", which i use for sorting the images in the table.
So, assuming you have a similar table, you will now need an interface from which you can alter the photo order. In this instance i usually have 2 links Up & Down, Up increments the photo position(ie incrementing the order_id) & Down does the opposite(decrementing the order_id).
So, once this is done, when you now retrieve the photos ensure you order them by order_id ASC or DESC. Then incorporate the code you have above.
I hope this points you in the right direction.

0

Hi everyone, thanks for your replies but I am not understanding where I should put your code.
Could you please post an example code.

Thanks!

1

Which way do you want to do this? Would you like to use a DB like wilch said or directly pull the list of files from the directory and put them on the page in order?

If you are using the scandir() like I mentioned in my previous post you would do it the same way as you have in your php code above.

<?php
if ($handle = scandir('photos/')) {
   foreach ($handle as $file)
   {
          if ($file != "." && $file != "..")
	  {     
          	
		$photos .= '<img src="thumbs.php?src='.$file.'&f=2&t=3" alt="'.$file.'" title="'.$file.'"/>';
          }
       }
  }

print $photos; 

?>

Edited by sudeepjd: n/a

1
$files = sort(glob('photos/*.jpg'));
foreach ($files as $file) {
  $photos .= '<img src="thumbs.php?src='.$file.'&f=2&t=3" alt="'.$file.'" title="'.$file.'"/>';
}

Edited by pritaeas: n/a

0

Many thanks for all your help, I have got them in the right order now!

Calum

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.