Jump to content

Dynamic Gallery


calvin182

Recommended Posts

Is there a way to make a gallery that I can update simply by placing the image in the directory and it will place the most recent image in the front (so it sorts the images in desending order by image name). I want to display the images in thumbnail format in rows of 4 and maybe about 6 rows per page.Does anybody know of any snippets that might help me out on this? I don't want one of those premade galleies like eSPG or Coppermine, I just want something that I can insert into my existing theme. Any snippets, tutorials, or ideas would really be a huge help to me please. Thank you!EDIT: I believe I have GD 2.0. I'd rather not do anything with MySQL if possible. I'm sure I won't be able to get every feature I want but any info on anything would be much appreciated.

Link to comment
Share on other sites

Have you ever thought about searching the net??????????????If it is just hard to type...then click here -> http://clusty.com/search?query=php+image+gallery+tutorialIt is amazing what all is on the internet... There are all these cool search engines that lead to all kinds of knowledge...BTW... did you follow the links to the php manual that hacknsnack gave???Read the examples given there for readdir()... just while you loop through, add the things you want to your array!

Link to comment
Share on other sites

I've searched the net but I havent found exactly what I am looking for so I thought that maybe I can post here and try to learn a little.In regards to the examples to readdir(), I obliviously read the examples because I ended up testing one out like I stated, but I don't understand how to put the data into an array. I am very new to PHP and I am trying to learn but everyonce in a while I need some help from somebody else... That's why I posted here :)

Link to comment
Share on other sites

Go ahead and post what code you have tested and we will help you make your modifications.As far as working with arrays:

<?php// first declare the array$imgs = array();// start your code that loops thru the filenames// add items to the array like this$imgs[] = $item_to_add;// after you have your array intact sort itsort($imgs);// then build your output?>

Check out php's sort().-hs

Link to comment
Share on other sites

the example of readdir() i've tested is:

<?php// Note that !== did not exist until 4.0.0-RC2if ($handle = opendir('/path/to/files')) {   echo "Files:\n";   /* This is the correct way to loop over the directory. */   while (false !== ($file = readdir($handle))) {       echo "$file\n";   }   closedir($handle);}?>

but what it does is it also returns directories, which I totally don't need, but to put them in the array, would I do somehting like:

<?php// Note that !== did not exist until 4.0.0-RC2if ($handle = opendir('/path/to/files')) {   echo "Files:\n";   /* This is the correct way to loop over the directory. */   while (false !== ($file = readdir($handle))) {       $imgs = array();       $imgs[] = $item_to_add;       sort($imgs);   }   closedir($handle);}?>

or would it be a different approach?

Link to comment
Share on other sites

You want to declare the array outside your loop and you can add a test for the dir's, and then do your sort after you have filled the array:

<?php$dir = '/path/to/files';$imgs = array(); if (is_dir($dir)) {    if ($dh = opendir($dir)) {        while (($file = readdir($dh)) !== false) {             if(($file != '.') && ($file != '..')) {                       $imgs[] = $file; }        }        closedir($dh);    }}sort($imgs);// you can use print_r() for debugecho "<pre>";print_r($imgs);echo "</pre>";?>

-hs

Link to comment
Share on other sites

okay so i've got it to sort in reverse order so the most recent image is placed atop and the olders on bottom using rsort(); heres what that looks like:

<?php$dir = '/home/******/public_html/gallery/nwb';$imgs = array();if (is_dir($dir)) {   if ($dh = opendir($dir)) {       while (($file = readdir($dh)) !== false) {            if(($file != '.') && ($file != '..')) {                      $imgs[] = $file; }       }       closedir($dh);   }}rsort($imgs);// you can use print_r() for debugecho "<pre>";print_r($imgs);echo "</pre>";?>

now i need to figure out how to make these in image format. what i want to do is put these into a 4x4 table (16 images per page). all in all this gallery is almost 6 pages. so i doubt theres a way to make it put the 16 most recent images always on the first page and so on so the last page has the oldest images because the script probably wouldnt autogenerate a new page when needed. is there a way to do that? if not putting all thumbnails on the same page will have to do.

Link to comment
Share on other sites

To get them to show up as images just use the values stored in your array as the src for your img tagsyou can use foreachYou could also just print out the img tags as you loop through the directory, instead of repeating the looping process again to go through an array.So instead of putting the images in an array you could just do this:

if (is_dir($dir)) {  if ($dh = opendir($dir)) {      while (($file = readdir($dh)) !== false) {           if(($file != '.') && ($file != '..')) {                     echo "<img src='$file' alt='Photo of something' />";            }      }      closedir($dh);  }}

If you want to use an array (so you can print them in reverse order) then just write the image tag while looping through the array somewhere else.I guess it would turn out to be something like

foreach($img as $img_file){     echo "<img src='$img_file' alt='Photo of something' />";}

Hope I remembered my php right... It's been a while...

Link to comment
Share on other sites

sweet, to recap, the script loads all images in the folder, puts them into an array, sorts the in reverse order, and displays them as images. here's what i've got at the moment:

<?php$dir = '/home/******/public_html/gallery/nwb/thumbnails';$imgs = array();if (is_dir($dir)) {   if ($dh = opendir($dir)) {       while (($file = readdir($dh)) !== false) {            if(($file != '.') && ($file != '..')) {                      $imgs[] = $file; }       }       closedir($dh);   }}rsort($imgs);// you can use print_r() for debug// echo "<pre>";// print_r($imgs);// echo "</pre>";foreach($imgs as $img_file){    echo "<img src='http://www.domain.com/gallery/nwb/thumbnails/$img_file' alt='Click here to view larger image' />";}?>

i havent set the anchor tags yet but i know how to do that stuff. now is there a way to load only a range of 16 to a page?

Link to comment
Share on other sites

My suggestion would be to calculate the total number of pages available with the tools:ceil()count()

....$total = count($imgs);$pages = ceil($total/16);// at the bottom of the page you can set up a links areafor($j = 1; j <=$pages; j++){   // echo your links however you want them formatted  // you would insert the Page No ( your url would end with ?p=$j )   }

You can set up the code to check for a $p variable in the url.

// set a default value$p = 1;// set a value if one was sentif(isset($_GET['p']))$p = $_GET['p'];// subtract one because the array index starts at 0$upperlimit = intval($p) * 16 - 1;// you will need to create the equation to get your start for each page$start = ...

So, are you sure you don't want to use an already made script. :) I'm betting that the google search that sbrownii suggested would include a script that has a "class" that would allow sorting by date like you are after.-hs

Link to comment
Share on other sites

first off i want to thank everybody who has been helping me on this one, you guys have really gone out of your way to help me out, and im glad there are people out there kind enough to help php noobs like me :)in regards to "So, are you sure you don't want to use an already made script."... yea i'm sure, i really dislike premade galleies because they are so generic, plus i don't learn anything. this approach, though difficult, is the best in my perspective because it caters to my exact needs and helps me understand how my site is going to work."I'm betting that the google search that sbrownii suggested would include a script that has a "class" that would allow sorting by date like you are after." php.net had a user contributed thing like that but the problem with that is i batch created all my images as thumbnails (and the main images) in irfanview so they all have the same date. they're all from my digi cam so by name will work.now, im following most of your code hacknsack, but the last line i don't get, what do you mean by create my own equation for the start? like... i think the next step is to tell the rest of the script to define a range of images to show depending on the value of $p, is that what you mean? but im not sure how to display a range from the array, ive been searching php.net but so far i havent found anything.i added an if statement to the for statement that creates the page links at the bottom so if the user is on page 1, then the link for page 1 in not active. heres where i am at:

<?php$dir = '/home/******/public_html/gallery/nwb/thumbnails';$imgs = array();if (is_dir($dir)) {  if ($dh = opendir($dir)) {      while (($file = readdir($dh)) !== false) {           if(($file != '.') && ($file != '..')) {                     $imgs[] = $file; }      };      closedir($dh);  }};rsort($imgs);// you can use print_r() for debug// echo "<pre>";// print_r($imgs);// echo "</pre>";foreach($imgs as $img_file) {   echo "<img src='http://www.domain.com/gallery/nwb/thumbnails/$img_file' alt='Click here to view larger image' />";};// set a default value$p = 1;// set a value if one was sentif(isset($_GET['p']))$p = $_GET['p'];// subtract one because the array index starts at 0$upperlimit = intval($p) * 16 - 1;// you will need to create the equation to get your start for each page// $start = ...$total = count($imgs);$pages = ceil($total/16);for ($j = 1; $j <= $pages; $j++) {if ($p!=$j) {echo "<a href=\"http://www.domain.com/gallery/nwb/index.php?p=$j\"> $j</a>";} else {echo " $j";};};?>

this is looking good, all thats left is to cut out a range of images to display :)EDIT: would array_slice() be used to return the range of 16 images after it is defined for the appropriate page?

Link to comment
Share on other sites

okay... i've some how figured out how to cut out my range of images, the last thing I need to do is populate the images into a 4x4 table.code is as follows:

<?php// set a default value$p = 1;// set a value if one was sentif(isset($_GET['p']))$p = $_GET['p'];$dir = '/home/domain/public_html/gallery/nwb/thumbnails';$imgs = array();if (is_dir($dir)) {  if ($dh = opendir($dir)) {      while (($file = readdir($dh)) !== false) {           if(($file != '.') && ($file != '..')) {                     $imgs[] = $file; }      };      closedir($dh);  }};rsort($imgs);$total = count($imgs);$pages = ceil($total/16);$prerangemin1 = $p * 16;$prerangemin = $prerangemin1 - 17;if ($prerangemin < 0) {$rangemin="0";} else {$rangemin=$prerangemin;};$output = array_slice($imgs, $rangemin, 16);foreach($output as $img_file) {   echo "<img src='http://www.domain.com/gallery/nwb/thumbnails/$img_file' alt='Click here to view larger image' />";};for ($j = 1; $j <= $pages; $j++) {if ($p!=$j) {echo "<a href=\"http://www.domain.com/gallery/nwb/index.php?p=$j\"> $j</a>";} else {echo " $j";};};?>

Edited by Jonas
Link to comment
Share on other sites

Recommend that you fill the array so that your table looks nice:

rsort($imgs);// fill the array so the table looks goodwhile((count($imgs) % 4) != 0){    $imgs[] = " ";}

Shout back if you need any help with the table layout.I don't want to spoil your fun, :) -hs

Link to comment
Share on other sites

im not sure what to do with that snippet... i know i gotta output $img_file as the image, and i'm actually going to output the image inside a table itself so i can add a frame around it, but i don't see how to output this. do i put the <td> stuff inside that space where &npsb; is and put <table> tags around the whole snippet? help please:)edit: do either of you have a first name and website I can credit for your help?

Link to comment
Share on other sites

This is what I came up with:

<?php$dir = '.';$imgs = array();if (is_dir($dir)) { if ($dh = opendir($dir)) {     while (($file = readdir($dh)) !== false) {          if(!is_dir($file)) {                    $imgs[] = $file; }     }     closedir($dh); }}rsort($imgs);// fill the array so the table looks goodwhile((count($imgs) % 4) != 0){    $imgs[] = " ";}$total = count($imgs);$pages = ceil($total/16);// set a default value$p = 1;// set a value if one was sentif(isset($_GET['p']))$p = intval($_GET['p']);// find upper limit for the pageif($p * 16 <= $total){    $upperlimit = $p * 16;    }    else {    $upperlimit = $total;    }echo "<p>$upperlimit and $total</p>\n";// set the start value of the index$start = ($p - 1) * 16;$j = $start;echo "<table>\n";while($j < $upperlimit){  echo "<tr>\n";      for($r = 0; $r < 4; $r++){        echo "<td>\n";            if($imgs[$j] != " ")            echo "<img src='http://www.domain.com/gallery/nwb/thumbnails/".$imgs[$j++]."' alt='Click here to view larger image' />\n";            else            echo $imgs[$j++]."\n";        echo "</td>\n";      }  echo "</tr>\n";}echo "</table>\n";echo "<p>";for ($j = 1; $j <= $pages; $j++) {      if ($p!=$j) {          echo "<a href=\"index.php?p=$j\"> $j</a>\n";          }          else {          echo " $j";          }}echo "</p>";?>

Probably easier than me trying to explain. :) You have done very well, :) -hs[edit] No credits for me please, just let me know if there are any errors in the code [/edit]

Edited by hacknsack
Link to comment
Share on other sites

oh that totally is awesome!!! Thank you SOOOO much! I think I can take it from here but if I need any help I'll make a post. Can I credit you for your help on my site? Just a first name and site url or email or just your name or whatever will do.You've gone way out of your way and I am very greatfull!EDIT: alright, but if you change your mind post here or PM me and I'll get on it, is it okay if I share this script on my site or something? no charing obliviously but i think it could be helpfull to some other people.

Link to comment
Share on other sites

okay here's a bit of a question... i want to put a link around the image that includes an img variable and a p variable. i tired:

echo "<a href=\'http://www.domain.com/gallery/nwb/show.php?img=".$imgs[$j++]."&p=$p' border='0'><img src='http://www.domain.com/gallery/nwb/thumbnails/".$imgs[$j++]."' alt='Click here to view larger image' /></a>\n";

but that reduces the images produced and fails to disable the border and the link is messed up so then i tried:

$imgsrc=$imgs[$j++]; echo "<a href=\'http://www.domain.com/gallery/nwb/show.php?img=$imgsrc&p=$p' border='0'><img src='http://www.domain.com/gallery/nwb/thumbnails/$imgsrc"' alt='Click here to view larger image' /></a>\n";

and that produced errors... any ideas?

Link to comment
Share on other sites

to fill anybody else in we found a few other issues and PM'd back and forth and came up with this as the result, I hope somebody can use this:INDEX.PHP:

<html><head><title>Oneity PHP Gallery</title></head><body><?php// ------------------------------------------------------------------------------------------------------// Title: ONEITY PHP GALLERY// Version: 1.0// File Name: index.php//   >>Required Files: show.php (included)// Author: Calvin Murphy, and members of w3schools.com forums// Last Updated: February 23rd, 2006 (3:41AM)// Website: [url="http://www.oneity-eight.roxr.com"]http://www.oneity-eight.roxr.com[/url]// Email: calvin182@gmail.com// ------------------------------------------------------------------------------------------------------// ------------------------------------------------------------------------------------------------------// Set up: ONEITY PHP GALLERY was created by Calvin Murphy with much help from the forum // members of [url="http://www.w3schools.com"]http://www.w3schools.com[/url]. This gallery was designed for digital camera users who // don't rename their images and want to display the most recent images first. Remember this is the first// version so theres no GD support amoung other things. For this script to function properly, the user // must set up a gallery folder, and within that folder there must be a folder for thumbnails (I recomend// calling it "thumbnails") and the full size images (I recomend calling it "imgs" or "images"). Both images// and thumbnails must have the same filename (including extension), the only difference is size and// location. For the thumbnails I recomend keeping the width of the images no more than 100pixels, but// there is no requirement. Place both files in the same directory. These files should not// be used used with include() or require() functions, but rather you should copy and paste your site// template around this block of php. For advanced users, filenames may be renamed.// ------------------------------------------------------------------------------------------------------//USER CONFIGURABLE ELEMENTS (these must be set correctly)// ------------------------------------------------------------------------------------------------------// set your domain and gallery directory. (ex: "http://www.domain.com" -no trailing slash)$domain = "http://www.domain.com/gallery";// set your thumbnails directory (if it is "http://www.domain.com/thumbnails", it'd just be "thumbnails")$thumbnails = "thumbnails";// thumbnails directory (as a relative address)$dir = '/home/YOURDOMAIN/public_html/gallery/thumbnails';// ------------------------------------------------------------------------------------------------------// ------------------------------------------------------------------------------------------------------// ADVANCED USERS// this file (defaultly named index.php)$index = "index";// show file (defaultly named show.php)$show = "show";// ------------------------------------------------------------------------------------------------------// ------------------------------------------------------------------------------------------------------// NO USER CONFIGUREABLE ELEMENTS (unless you know what you're doing!)// ------------------------------------------------------------------------------------------------------// ------------------------------------------------------------------------------------------------------$imgs = array();// opens image directoryif (is_dir($dir)) {if ($dh = opendir($dir)) {while (($file = readdir($dh)) !== false) {if(!is_dir($file)) {$imgs[] = $file; }}closedir($dh);}}// sorts images in reverse orderrsort($imgs);// fill the array so the table looks goodwhile((count($imgs) % 4) != 0){$imgs[] = " ";}// calculations$total = count($imgs);$pages = ceil($total/16);// set a default value$p = 1;// set a value if one was sentif(isset($_GET['p']))$p = intval($_GET['p']);// find upper limit for the pageif($p * 16 <= $total){$upperlimit = $p * 16;}else {$upperlimit = $total;}// set the start value of the index$start = ($p - 1) * 16;// tell user how far in the gallery they are$start1= $start + 1;echo "<p>displaying images $start1 to $upperlimit out of $total</p>\n";// builds image$j = $start;echo "<table>\n";while($j < $upperlimit){echo "<tr>\n";for($r = 0; $r < 4; $r++){echo "<td align='center' valign='middle'>\n";if($imgs[$j] != " ")echo "<a href='$domain/$show.php?img=".$imgs[$j]."&p=$p'><img src='$domain/$thumbnails/".$imgs[$j++]."' alt='Click here to view larger image' border='0'/></a>";elseecho $imgs[$j++]."\n";echo "</td>\n";}echo "</tr>\n";}echo "</table>\n";echo "<p>";for ($j = 1; $j <= $pages; $j++) {if ($p!=$j) {// ALMOST DONE! - creates page linkingecho "<a href=\"$domain/$index.php?p=$j\"> $j</a>\n";}else {echo " $j";}}echo "</p>";//FINISHED WOOT?></body></html>

SHOW.PHP:

<html><head><title>Oneity PHP Gallery</title></head><body><?php// ------------------------------------------------------------------------------------------------------// Title: ONEITY PHP GALLERY// Version: 1.0// File Name: show.php//   >>Required Files: index.php (included)// Author: Calvin Murphy, and members of w3schools.com forums// Last Updated: February 23rd, 2006 (3:44AM)// Website: [url="http://www.oneity-eight.roxr.com"]http://www.oneity-eight.roxr.com[/url]// Email: calvin182@gmail.com// ------------------------------------------------------------------------------------------------------// ------------------------------------------------------------------------------------------------------// Set up: ONEITY PHP GALLERY was created by Calvin Murphy with much help from the forum // members of [url="http://www.w3schools.com"]http://www.w3schools.com[/url]. This gallery was designed for digital camera users who // don't rename their images and want to display the most recent images first. Remember this is the first// version so theres no GD support amoung other things. For this script to function properly, the user // must set up a gallery folder, and within that folder there must be a folder for thumbnails (I recomend// calling it "thumbnails") and the full size images (I recomend calling it "imgs" or "images"). Both images// and thumbnails must have the same filename (including extension), the only difference is size and// location. For the thumbnails I recomend keeping the width of the images no more than 100pixels, but// there is no requirement. Place both files in the same directory. These files should not// be used used with include() or require() functions, but rather you should copy and paste your site// template around this block of php. For advanced users, filenames may be renamed.// ------------------------------------------------------------------------------------------------------//USER CONFIGURABLE ELEMENTS (these must be set correctly)// ------------------------------------------------------------------------------------------------------// set your domain and gallery directory. (ex: "http://www.domain.com" -no trailing slash)$domain = "http://www.domain.com/gallery";// set your thumbnails directory (if it is "http://www.domain.com/thumbnails", it'd just be "thumbnails")$thumbnails = "thumbnails";// set the full size image directory$img = "img";// thumbnails directory (as a relative address)$dir = '/home/YOURDOMAIN/public_html/gallery/thumbnails';// ------------------------------------------------------------------------------------------------------// ------------------------------------------------------------------------------------------------------// ADVANCED USERS// index file (defaultly named index.php)$index = "index";// this file (defaultly named show.php)$show = "show";// ------------------------------------------------------------------------------------------------------// ------------------------------------------------------------------------------------------------------// NO USER CONFIGUREABLE ELEMENTS (unless you know what you're doing!)// ------------------------------------------------------------------------------------------------------// ------------------------------------------------------------------------------------------------------// set a default value$p = 1;$img="none";// set a value if one was sentif(isset($_GET['p']))$p = intval($_GET['p']);if(isset($_GET['img'])){$img = $_GET['image']} else {header("Location: $domain/$index.php"); exit(0);};<a href="$domain/$index.php?p=<?php echo $p;?>"><Back to gallery</a><br /><img src="$domain/$img/<?php echo "$img";?>" alt="img" hspace="0" vspace="0" border="0" />?></body></html>

Edited by Jonas
Link to comment
Share on other sites

does anybody have an idea on how to make back and next buttons to scroll though the images on the show page?i think this would involve these functions: in_array, next, and prev. so i think i would take the $img and use that with in_array and then use next and prev. but i think i would have to get the array again.i have created a backend control panel to control almost every aspect of this gallery so i cannot change the structure of the script for the back/next buttons

Link to comment
Share on other sites

How about passing the current image name back to php, use array_search to grab the current index then -- or ++ check to be sure that index exists, if it does send it, if it does not let them know they are either at the end or beginning.Be sure to check this post concerning "false" conditions:http://us3.php.net/manual/en/function.array-search.php#61666-hs

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...