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

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.

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.

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!

Anyone?

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; 

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

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

Calum

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.