Tutorial: Dynamic slideshow with PHP & JQuery 102

When I set out to add database driven player info at NuggetsHoops.com, I knew that I wanted to include code that would display some of the many images that I had set aside for each NBA player. I also knew that I would continue to add new pictures. Application code that could easily display old and new images, without additional effort for each added image would work best.

I had already written PHP code that could look at a folder and create a list of images to be displayed. When I ran across the powerful jQuery Cycle Plugin, I had found a great way to display them.

Let’s get coding. This tutorial depends on PHP 5, jQuery 1.2.3 or later, jQuery Cycle Plugin version 2.51 or later.

Add the following Javascript to your PHP/HTML to enable and call the Cycle Plugin:



Note that there are many options and styles of animation provided by the powerful Cycle plugin.

Add the following PHP to iterate over any folder and dynamically generate img tags using any images found in the folder:
$directory = 'images/players/' . $row['imageName'];
try {
// Styling for images
echo "

";
foreach ( new DirectoryIterator("../" . $directory) as $item ) {
if ($item->isFile()) {
$path = "/" . $directory . "/" . $item;
echo "";
}
}
echo "

";
}
catch(Exception $e) {
echo 'No images found for this player.
';
}

Any img tags within an HTML element of class ‘myslides’ (or whatever you initialized the Cycle plugin with in the Javascript) will have the slideshow behavior added to it. The $row array on line 1 is referencing a database query result, but could be set in a number of ways for your specific needs. The DirectoryIterator reference on line 5 is a builtin class in PHP5.

Here’s the CSS to style the images being displayed in the slideshow:

#myslides {
width: 340px;
float: right;
padding: 0;
margin: 0 auto;
margin-top: 20px;
}

#myslides img {
padding: 10px;
border: 1px solid rgb(100,100,100);
background-color: rgb(230,230,230);
width: 320px;
top: 0;
left: 0
}

So, there’s a very quick walk thru a working example to generate a dynamic slideshow from any folder of images. If you’d like a full download of the code, or any further explanation, please leave a comment!

You can see this code in action by just clicking on any player’s name at the NuggetsHoops.com Roster page.

New – download the code for this Tutorial

[download#WithImage id=”1″]

Demo

102 thoughts on “Tutorial: Dynamic slideshow with PHP & JQuery

  1. Reply jjmc Jun 2,2009 2:20 AM

    Hi developer,

    I have just test your code above.. and I have already put all the images under images/players/ and put all the images like 1.jpg, 2.jpg..etc.. and same as you did. how come it doesn’t work it always display “No images found for this player.”

  2. Reply jjmc Jun 2,2009 2:21 AM

    Hi developer,

    I have just test your code above.. and I have already put all the images under images/players/ and put all the images like 1.jpg, 2.jpg..etc.. and same as you did. how come it doesn’t work it always display “No images found for this player.” can you email me the source code for this.. I like jquery so much

    thanks and regards

  3. Reply alan Jun 2,2009 11:48 PM

    jjmc,

    Make sure the path to your images folder is correct, based on lines 1 and 5 in the PHP source. I had to add “../” in the arg sent to the DirectoryIterator because my PHP file was in a subfolder, so the path to get to my images folder was ../images/players/anthony and so on. That path is relative to where your PHP file is on your server.

    Hope that helps! I’ll be happy to post the full source here, but won’t be able to get to that for another day or two.

  4. Reply jjmc Jun 7,2009 5:42 AM

    thanks developer for replying.. what I’ve got now is that it is now displaying the image..but my problem now is that , it is animating. it’s only shows the image.

    also is it possible to do some descriptions everytime it loads the image.. can we do like that.. here is the code that i have..

    can you help me on this please…or any suggestions

    Untitled Document

    $(document).ready(function(){
    $(‘#myslides’).cycle({
    fit: 1, pause: 1, height: 360
    });
    });

    #myslides {
    width: 340px;
    float: right;
    padding: 0;
    margin: 0 auto;
    margin-top: 20px;
    }

    #myslides img {
    padding: 10px;
    border: 1px solid rgb(100,100,100);
    background-color: rgb(230,230,230);
    width: 320px;
    top: 0;
    left: 0
    }

    <?php

    $directory = ‘/test/images/players/’ . $row[‘imageName’];
    try {
    // Styling for images
    echo “”;
    foreach ( new DirectoryIterator(“../” . $directory) as $item ) {
    if ($item->isFile()) {
    $path = “/” . $directory . “/” . $item;
    echo “”;
    }
    }
    echo “”;
    }
    catch(Exception $e) {
    echo ‘No images found for this player.’;
    }

    ?>

  5. Reply san Aug 30,2009 12:28 PM

    include (‘db_connect.php’);

    $select=mysql_query(“select * from images”);
    while($row=mysql_fetch_array($select))
    {
    $directory = ‘images/players/’ . $row[‘pic’];
    try {
    // Styling for images
    echo “”;
    foreach ( new DirectoryIterator(“../../” . $directory) as $item ) {
    if ($item->isFile()) {
    $path = “/” . $directory . “/” . $item;
    echo “”;
    }
    }
    echo “”;
    }
    catch(Exception $e) {
    echo ‘No images found for this player.’;
    }
    }

    ?>

  6. Reply san Aug 30,2009 12:30 PM

    can u please help me to debug this code.

    my image is under images/player/pic1.jpg

    am having this on my browser as result
    No images found for this player.
    thanks you

  7. Reply alan Sep 1,2009 12:11 AM

    San,

    It appears that your image and your directory code are not in sync. On line 7, from my example I was looking for player images in “images/players/…” while you’ve stated that placed your image in “images/player/…”.

    If that’s not your issue, can you provide a link to where you are trying this?

    Alan

  8. Reply san Sep 1,2009 3:11 AM

    hello
    am new with php and am getting confused

    my main folder is images
    and my images is in the folder player

    can u please tell me how to write it???

    thanks you..
    u r so nice

  9. Reply san Sep 1,2009 4:06 AM

    thanks a lot Sir,

    now it is working and i have found my mistake..

    but with your code, the slideshow is taking all the picture in the folder and displaying it.

    but me i want to take picture that are from a dataabase

    my code

    $select=mysql_query(‘select photosproduit from produit where isslide=’1”)

    please help me to implement this part in my code..
    thank you

  10. Reply alan Sep 2,2009 8:02 AM

    Excellent – glad to hear that you got it working! I was about to post that I will be adding a zipfile of the code from this tutorial to make it easier for people to get started.

    As for pulling images from a database – are you storing the entire binary image in the database or just the path to the image on your server?

  11. Reply san Sep 2,2009 11:08 AM

    Thank You
    the path of the images that is inserted in the database is uploads/picture1.jpg
    and the folder uploads is on my server.

    can you help me please..

  12. Reply timska77 Oct 8,2009 10:38 PM

    Hello,
    Your script is awesome. Coupling jQuery and PHP for a slideshow like this is perfect. The only problem that I encountered is that with this code Safari loads each image onto the page for a little while until all of the images are loaded and then switches to a single image and runs the slideshow as it should. Any ideas on how to solve this? Safari is a PITA but as a mac user I always try to accommodate it.

  13. Reply indialike Dec 14,2009 4:29 AM

    Very nice and useful tutorials to web designers,
    Thanks for posting.

  14. Reply alan Jan 6,2010 1:08 AM

    timska77 – Thanks! Strange – I don’t see that behavior in Safari 4 on Mac or PC. Are you seeing this issue with an older version of Safari?

    Here’s my test example, which uses a slightly modified version of the code from this tutorial:

    http://www.nuggetshoops.com/players/view.php?pid=1

  15. Reply Ibrahim Odeh Jan 30,2010 12:41 PM

    Really,

    Great jobs 1 million kisses & hugs is not enough for you

    Appreciate your efforts.

    Thank you very much

  16. Reply sathya Apr 22,2010 2:47 AM

    Appreciate your efforts.

    Thank you very much

  17. Reply Bruce May 20,2010 10:17 PM

    thanks a lot Sir,

    now it is working and i have found my mistake..

    but with your code, the slideshow is taking all the picture in the folder and displaying it.

    but me i want to take picture that are from a dataabase

    my code

    $select=mysql_query(‘select photosproduit from produit where isslide=’1”)

    please help me to implement this part in my code..
    thank you

  18. Reply Bruce May 21,2010 10:59 PM

    Appreciate your efforts.

    Thank you very much

  19. Reply Alex May 28,2010 8:41 AM

    How come in Safari when this first loads it displays the little “image not found” icon, but then proceeds to play the slideshow. Any ideas how to solve this? Other than that this script is absolutely perfect and exactly what I was looking for.

    Cheers

  20. Reply alan May 28,2010 9:30 AM

    I’m unable to reproduce that issue, but I’m testing with Safari 4.0.5 on Windows. Are you seeing the problem on a Mac, or on a different version of Safari? I can test on a Mac this weekend and see if I can reproduce it there.

    Are you seeing the broken image when running my demo page, or when trying the script on your own?

  21. Reply Alex May 31,2010 6:08 PM

    I am using a Mac. It only shows when I use the script on my own with my own images. On your demo page it runs fine and completely unaltered it runs fine as well. Thanks for the swift response, you’re awesome.

    Cheers

  22. Reply lugi Jun 1,2010 4:01 AM

    hey i am trying to implement the jquery cycle plugin in my project and i get the following error when trying to run it

    ” Undefined variable: row ”

    my diresctory points to ‘../images/clients/’

    any help?

  23. Reply Dorsey Prouse Jun 4,2010 9:30 PM

    I would like to comment on this blog by adding that web standard are greatly important. Take a look at what is currently happening between HTML5 and Apple.

  24. Reply Software Jun 28,2010 10:23 AM

    Congratulations! You have just won a new feed reader 🙂 .. really awesome article, Mike.

  25. Pingback: 60 Awesome jQuery Tutorials | Web.Dtuts - Web Development Tutorials

  26. Reply jingle Jul 8,2010 11:51 PM

    how can you do the same thing but showing on a 3 rows basis, one row is very easy , all the Cycle stuff works on one row but when it comes to fetching database and showing three rows is a nightmare

  27. Pingback: 75+ jQuery Plugins: Download Powerful and Elegent jQuery Plugins & Tutorials | jQuery | Graphic Design Junction

  28. Reply KP Jul 19,2010 4:22 PM

    Hi:

    I’ve been looking for a php script that automates jQuery slideshows. this is a gem of a find. thank you.

    I have a quick question. I’m using this script in a cms. Any image upload will generate an auto thumbnail. how can i modify the php code to bypass the thumbnails? currently, both image1.jpg and thumb_image1.jpg are showing.

    thank you.

  29. Reply alan Jul 22,2010 1:31 AM

    jingle:

    Do you want to show 3 images at the same time, but pull them from a database rather than a folder on the server?

    KP:

    You should be able to just add a regexp to the if statement that checks if the current item is a file in the PHP file… that will filter out your auto-generated thumbnails from the CMS.

    Try this new version of line 6:
    if ($item->isFile() && !preg_match(‘/^thumb_/’, $item)) {

    I also created a new demo to show it working. The top slideshow will display the thumbnail, the bottom one doesn’t.

  30. Reply KP Jul 23,2010 7:21 PM

    Hey Allan:

    I’m no php programmer so let me make sure i understand.

    I should replace

    $directory = ‘uploads/images/slideshow’ . $row[‘image’];
    try {
    // Styling for images

    echo “”;
    foreach ( new DirectoryIterator(“” . $directory) as $item ) {
    if ($item->isFile()) {
    $path = “/newsite/” . $directory . “/” . $item;
    echo “”;
    }
    }
    echo “”;
    }

    catch(Exception $e) {
    echo ‘No images found for this player.’;
    }

    WITH
    $directory = ‘uploads/images/slideshow’ . $row[‘image’];
    try {
    // Styling for images

    echo “”;
    foreach ( new DirectoryIterator(“” . $directory) as $item ) {
    if ($item->isFile() && !preg_match(‘/^thumb_/’, $item)) {
    $path = “/newsite/” . $directory . “/” . $item;
    echo “”;
    }
    }
    echo “”;
    }

    catch(Exception $e) {
    echo ‘No images found for this player.’;
    }

  31. Reply KP Jul 24,2010 12:28 PM

    Alan:

    sorry to bother. I get an error with the new php line. My code currently reads:

    $directory = ‘uploads/images/slideshow/’ . $row[‘imageName’];
    try {
    // Styling for images
    echo “”;
    foreach ( new DirectoryIterator(“” . $directory) as $item ) {
    // if ($item->isFile()) {
    if ($item->isFile() && !preg_match(‘/^thumb_/’, $item)) {
    $path = “/newsite/” . $directory . “/” . $item;
    echo “”;
    }
    }
    echo “”;
    }

    catch(Exception $e) {
    echo ‘No images found for this player.’;
    }

    the error is:
    # invalid code entered.
    # Parse error: syntax error, unexpected ‘^’ eval()’d code on line 7

    any ideas? the website is http://keepsakefamilytreevideo.com/newsite/

    thanks for your help.

    kp

  32. Reply alan Jul 26,2010 10:24 AM

    No problem KP – I’m happy to try and help. I think the issue might be from the way my WordPress theme has styled the characters, or the way I cut and paste the code sample.

    Make sure the quote right after !preg_match is not the back-tick character. It should be a straight single quote. I think that’s why you are getting a syntax error from PHP. The ending quote also needs to be a single quote.

    Let me try again to show that line of code here:

    if ($item->isFile() && !preg_match(‘/^thumb_/’, $item)) {

    Basically, what that line of code does is check to see if the current item in the loop IS a file and IS NOT a file starting with the name “thumb_”.

    NOTE: After posting this comment, I can see it has the same issue… must be something in this theme that I need to look into. Anyway, on your keyboard, make sure you replace the quote after !preg_match( with the one below the double quotes key next to the Enter key on a standard keyboard. Also fix the ending quote immediately after ^thumb_/. If this doesn’t work, I’ll try and post the entire example file here as a download this week.

    Let me know how it goes!

  33. Reply KP Jul 29,2010 11:01 AM

    Alen:

    Got it fixed. yes, it does need to be single quote. I don’t see very well and I did not notice the quotes were wrong. thanks for helping.

  34. Reply KP Jul 29,2010 11:02 AM

    Alen:

    Got it fixed. yes, it does need to be single quote. I did not notice the quotes were wrong. thanks for helping.

  35. Reply Niels Aug 13,2010 2:30 AM

    Alan,

    Great article, but I’ve problems with the $(document).ready(function()-function in all latest browsers: all images load shortly before the WordPress-page loads.
    It’s very frustrating, because I’ve read a lot of articles about this problem.
    Can you help me ?

    The code in header.php:

    $(document).ready(function(){
    $(‘#myslides’).cycle({
    fit: 1, pause: 2
    });
    });

    <?php
    $directory = 'wp-content/themes/iblog2/images/slideshow/' . $row['imageName'];
    try {
    // Styling for images
    echo "”;
    foreach ( new DirectoryIterator($directory) as $item ) {
    if ($item->isFile()) {
    $path = $directory . “/” . $item;
    echo “”;
    }
    }
    echo “”;
    }
    catch(Exception $e) {
    echo ‘No images found for this slideshow.’;
    }
    ?>

    Thanks in advance,

    Niels

  36. Reply Alex Aug 17,2010 9:29 PM

    For anyone that was experiencing the same problem as me, I finally figured out the one broken image thing, it was because the slideshow was taking the .DS_store hidden file in the folder as an image and trying to display it, so deleting it did the trick. I feel pretty stupid lol

  37. Reply Alexpt Aug 19,2010 2:39 AM

    I was looking for that php code.. works fine.. tks

  38. Reply Michael Sep 7,2010 11:01 PM

    G’day Alan,

    Works great – I simplified the CSS for a borderless display and wrote in an Auto-refresh line as well. One question though – what would be a straight forward way for this to support multiple formats, possibly PDF or MP4? I assume you’d have to link the libraries/players for those formats into the script..

    Cheers,
    Michael

  39. Reply Michael Sep 8,2010 11:08 PM

    And here’s one more tricky one.. Is there any way to get the PHP script to auto-generate a new page and refresh when content is changed in the image directory? Trying to save bandwidth by not getting our script to auto refresh every 10 mins.

  40. Reply Kenneth Feb 9,2011 7:22 PM

    The code is good except for the problem of not showing the first/last image. Using your own images works fine but using else images causes this problem. I wonder why it should be this way. Well done for the good job but this problem has stopped me from using the code. Thanks again…

  41. Reply Tim Feb 17,2011 10:58 AM

    This is great, thanks for that. I added a small line to check for the file extension of the files in the directory. This will only output files that end in “.jpg”:

    foreach ( new DirectoryIterator($directory) as $item ) {
    if ($item->isFile()) {
    //get the file extension
    $fileExt = substr($item, strrpos($item, ‘.’) + 1);
    //only display files that end in jpg
    if ($fileExt == ‘jpg’) {
    $path = $directory . “/” . $item;
    echo “”;
    }
    }
    }

  42. Reply Gabe Mar 5,2011 11:20 AM

    I am getting the following parse error:

    Parse error: syntax error, unexpected ‘{‘ in /home/vg008web07/94/29/2912994/bhamfashionweek/web/fullsite000/index.php on line 100

    Any ideas as to what the deal is? Here is my php:

    [code]
    <?php
    $directory = 'images/slideshow/' . $row['imageName'];
    try {
    // Styling for images
    echo "”;
    foreach ( new DirectoryIterator(“../” . $directory) as $item ) {
    if ($item->isFile()) {
    $path = “/” . $directory . “/” . $item;
    echo “”;
    }
    }
    echo “”;
    }
    catch(Exception $e) {
    echo ‘No images found for this player.’;
    }
    ?>
    [/code]

    • Reply alan Mar 5,2011 11:26 AM

      Gabe: I can’t spot an error, and an online PHP syntax checker doesn’t detect any either in your code.

      Two questions:

      1. What version of PHP is your server running? You can check with your host provider or run php_info(); on your page to see a report.

      2. What line in your PHP does line 100 appear to point to?

  43. Reply Gabe Mar 5,2011 11:41 AM

    Ahh, it was the PHP version. Upgraded and all is working. So sorry to miss something so small!

    Also, thanks for your speedy response!!! Great plugin/work!

  44. Reply alan Mar 5,2011 11:49 AM

    Gabe: Excellent – glad you got it working… no worries at all Happy coding!

  45. Reply Victor Mar 11,2011 5:56 AM

    Awesome code, working fine for me, thanks for sharing…..

  46. Pingback: Free jQuery Plugins Tutorails | Free download softwares, music, wordpress template, joomla template, Jquery tools and tips, Beauty tips, Free online video..

  47. Reply treck Apr 23,2011 7:53 AM

    The problem is that when you get the filename of the first image, it includes the .DS_Store file. So if you’re directory is www/images/, the first file will read as, www/images/.DS_Store. You have to check to make sure that it only includes .jpg, .png etc …

    • Reply alan May 16,2011 4:40 AM

      treck:

      I’ve got an updated version of the script that only displays files with certain extensions working. I just need to do a little more testing with it and then I’ll update the page with a new download verison.

      Alan

  48. Reply blex May 1,2011 8:21 PM

    is there a way to make this compatible with jquery 1.4.2?

  49. Reply blex May 1,2011 10:07 PM

    also, my slideshow sits in a header file that way it will always display no matter what page, however the current path “images/slideshow/” only works on the homepage because its appended to the base url “example.com” but when you go to another page “example.com/page1” it doesn’t load because i’m assuming it’s searching for “example.com/page1/images/slideshow/”. anyway around this?

    • Reply alan May 16,2011 4:22 AM

      blex – as for the slideshow in a header file and it handling different paths, you could update the line that says:

      $directory = ‘images/slideshow/’;

      to be something like this:

      $directory =’/images/slideshow/’;

      That way the script would always look for the images folder in the root of your domain. If that doesn’t solve the problem for you, let me know and I’ll work out a way to make the script more flexible or take the path as an optional argument related to the current page the php file is getting loaded from.

  50. Reply Alok May 3,2011 5:03 AM

    Really good code but a single problems :

    When i used this slide show a blank image run in my script name
    Thumb.jpg i don’t understand this error

    Please help me

  51. Reply Ssemwanga May 18,2011 4:12 AM

    when i do as you demonstrated i got no error but again there no image playing so what can i do

    • Reply alan May 18,2011 10:12 AM

      Ssemwanga – is this your first comment here? You make it sound as if you have tried this tutorial more than once with no success.

      Do you see the message “No images found for this player” on the page where you are trying to create the slideshow? Do you see other text on the page (that you wrote) or is it blank?
      Do you have access to your server logs?

      Another idea is to try adding a small snippet of PHP code *after* where you are attempting to display the slideshow. In this way, you can see if the slideshow is causing an error in PHP where it won’t continue to process PHP code on your page.

      Just add something like this

  52. Reply Lorrie Gilboy Jun 2,2011 6:35 PM

    Hey, I really don’t think saying this on your post Tutorial: Dynamic slideshow with PHP & JQuery would be the appropriate place but I couldn’t locate a contact page form within your somewhat messy theme (sorry). My readers would always tell me exactly the same thing so I switched over to a new theme from http://tinyurl.com/themeforestz. I’ve only gotten kind comments after. Regards, Lorrie Gilboy

  53. Reply Iomoio Jun 5,2011 5:19 AM

    I know this is really boring and you are skipping to the next comment, but I just wanted to throw you a big thanks – you cleared up some things for me!

  54. Reply Tamika Hunstiger Jun 12,2011 9:37 PM

    good blog man, I really admire your writing style that you are using for your posts and stuff, really hollywood…

  55. Reply gare Jun 16,2011 8:36 AM

    Hi Alan,

    Thanks for the clearly written demo. To be honest, the download package is a total winner! An entire working example to reverse engineer!

    Awesome.

    Keep up the great work. I’ll look around your site briefly to click on some ads, if you have any. 🙂

    gare

  56. Reply William Rouse Jun 16,2011 7:32 PM

    It would be nice to add a Next and Back button. How would you do this?

    • Reply alan Jun 16,2011 11:29 PM

      William – I think that would be doable. I’ll take a crack at adding that and adding it as a configuration option. I’ll update the tutorial and the download if I can work it out in the next week or so, and add a comment. Check back in a few!

  57. Reply William Rouse Jun 21,2011 7:03 PM

    Thanks for looking into it Alan.
    WBR

  58. Reply طراحی سایت Jul 24,2011 2:49 AM

    please put slideshows that independence from languages

  59. Reply Stray Aug 25,2011 4:59 PM

    This is great. Thank you! I’ve been trying to make a JQuery/PHP slideshow work for one of my clients and this tutorial is so clear and useful. Working wonderfully.

  60. Reply Renu Nov 22,2011 12:57 PM

    Hi Allan

    I went through the tutorial and its a real help for someone whose new to php and jquery too. I wanted a help regarding the slideshow content. Is there any way through which we can also add content for the slideshow as per the image. I appreciate any quick response from your side.

    Thanks in advance.

    Renu.

    • Reply alan Nov 22,2011 1:20 PM

      Renu – are you asking about having text or html associated with each image in the slideshow? If so, yes… have definitely thought about that for my own use. I haven’t come up with a clean solution that wouldn’t take away from the easy way of adding new content that I have in place right now though. One thought would be to have the slideshow code look for a file like “descriptions.txt” that it could parse and add descriptions/captions for any matching filenames in that file. If it didn’t find one, it would still just show the image as it does today. If that sounds good I’ll add that to my future features for this tutorial and post an update in a future version.

  61. Reply san Feb 22,2012 3:29 AM

    Hello alan,

    After the end of the slideshow, i don’t want to see the border without picture. Please can you help me how to add line of code to keep the images in the loop.>?

    Thank you

  62. Pingback: What is the easiest way to put a photo gallery into an existing website? » free icons download

  63. Reply Daan Apr 25,2012 9:44 AM

    hello alan,
    i got the scriptt but i see all the pictures but they are under each other.
    can you help me?

    • Reply alan Apr 25,2012 1:37 PM

      Can you tell me what browser (FF, IE, Chrome) and version you are seeing the issue in?

      Also, if it’s possible, please share a link to the page where you are trying to use the slideshow.

  64. Reply subimal Jun 20,2012 9:43 AM

    Kindly tell me how to choose the images randomly from the folder for the slide show

  65. Pingback: 开发者经常用到的75 个功能强大的 jQuery插件和教程汇总(上篇) - TNM博客 - 知其然知其所以然 | 做而且还要做好 | 知足常乐

  66. Pingback: 开发者经常用到的75 个功能强大的 jQuery插件和教程汇总(上篇) | 编程·早晨

  67. Reply Survi Jan 3,2013 11:11 PM

    How can i use it in wordpress?Please suggest me something to include slides view dynmically for wordpress.

  68. Reply sam Jan 12,2013 2:40 AM

    Great tutorial, workes like a charm.
    ONe thing though: I can’t figure out what determines the order of the images from the imagefolder… It seems random now, or based on filesize or so, but I’d like the slideshow to display them alphabetically… Should probably use a sort command in the php code, but how?? all help welcome

    • Reply alan Jan 14,2013 4:52 AM

      A few changes are needed in the PHP code to provide an alphabetical sort.

      Replace lines 5-10 (see above in the PHP code snippet) with the following, and you should have what you are looking for:

      $itr = new SortingIterator( new FilesystemIterator($directory), ‘strnatcasecmp’);
      foreach ($itr as $myfile) {
      if ($myfile->isFile()) {
      //echo $myfile->getPathname() . PHP_EOL;
      $path = $directory . “/” . $myfile->getFilename();
      echo “<img src=\”” . $path . “\” />”;
      }
      }

      Then add the following snippet somewhere above, just below the start of the PHP tag.

      class SortingIterator extends ArrayIterator
      {
      public function __construct(Traversable $iterator, $callback)
      {
      if ( ! is_callable($callback)) {
      throw new InvalidArgumentException(sprintf(‘Callback must be callable (%s given).’, $callback));
      }

      parent::__construct(iterator_to_array($iterator));
      $this->uasort($callback);
      }
      }

      I will try to package this up better in a new download when I have more time.

  69. Reply sam Jan 13,2013 2:36 PM

    okay,
    With all my basic knowledge I rewrote the php part to using an array that I can sort. The array than gets printed, and yields the exact same results as the previous scripts, so a div with image tags, the PROBLEM:
    the image tags are not picked up by the js script… why not, all image tags should be picked up right?

    hoping for help here
    as a reminder, the initials problem is that I want the slide show to be alphabetically..

    Thanks, best Sam

    • Reply alan Jan 14,2013 5:00 AM

      Sam,

      All images are picked up by the javascript as long as they are contained in an element that matches the selector in the call to cycle().

      In my download, I created a div with the id of “myslides” and had the selector look for that with this code:

      $(‘#myslides’).cycle({
      fit: 1, pause: 2
      });

      Hope that helps!

  70. Reply uberdood Jan 22,2013 7:00 PM

    Do you have a working version with back/forward buttons yet?

  71. Reply Gaby Apr 4,2013 9:06 AM

    Hello, I first want to say how amazing you are. Thank you thank you thank you for posting this. I’ve been trying to find a way to make this possible. ANYWAY, I have a HUGE image folder, and I want to only show the 10 most current images(the camera is connected to an ftp server that automatically takes pictures every hour and uploads it to the folder). Is there a way to tweak the code for that?

    • Reply alan Apr 5,2013 11:36 PM

      Hi Gaby,

      Thanks for the kind words.

      This is un-tested, but here’s what I would do to modify the PHP code to grab the 10 latest images in a folder: (replacement of lines 5-10 in the PHP code above)

      $images = array();
      foreach (scandir($directory) as $node) {
      $nodePath = $directory . DIRECTORY_SEPARATOR . $node;
      if (is_dir($nodePath)) continue;
      $images[$nodePath] = filemtime($nodePath);
      }
      arsort($images)
      $newest = array_slice($images, 0, 10);

      Then you can just iterate over the array:

      foreach ($newest as $imageFile) {
      $path = “/” . $directory . “/” . $imageFile;
      echo ““;
      }

  72. Reply fred Apr 4,2013 8:11 PM

    doesnt seem to work

    • Reply alan Apr 5,2013 11:44 PM

      Fred,

      Other people have had success with it here. Can you share a few more details so that I can try and help? What browser are you using? Do you see any errors in the console of your browser when you view your test page? Try adding the Firebug plugin to Firefox for debugging purposes – it is very helpful.

  73. Pingback: 开发者经常用到的75 个功能强大的 jQuery插件和教程汇总(上篇) | news snack

  74. Reply Alexander Jul 10,2013 2:35 PM

    How do i center the slideshow?
    So it doesn’t matter how big the image is, every image is perfectly in the middle of the webpage.

  75. Reply eazybuzy Jul 20,2013 12:01 AM

    Hello,

    Thanks for the good work.

    I used to it and it worked on localhost, but once i am online it doesnt work anymore. it displays perfectly while i am online but when internet access is enabled, it just displays all the pictures below each other and it doesnt change.

    please help with any idea as to how to go about this.

  76. Reply eazybuzy Jul 20,2013 5:26 PM

    Thanks Alan , I have been able to resolve the issue, the reported error was

    Uncaught TypeError: Object [object Object] has no method ‘cycle’

    so i modified the script to

    $(document).ready(function(){
    $.getScript(‘/js/jquery.cycle.all.min.js’, function(){
    $(‘#myslides’).cycle({ fit: 1, pause: 2 });
    });
    });

  77. Reply Ashish Solanki Oct 7,2013 12:31 AM

    It really helps thank you

  78. Reply imran ali Dec 7,2013 2:45 AM

    hey frnds i am new here tell me how create flexible slider in php and jquery use and how use .htaccess file in php

  79. Reply jocelin Louis Feb 6,2014 5:47 AM

    Hi guys,can you please help?how can i add url to these images so that each image point to a new page?

  80. Reply leonardito Dec 4,2014 4:46 PM

    How can I incorporate this code in responsive design using DIV.
    Thanks for reply and Greetings.

  81. Reply Paddy H Dec 21,2014 5:46 PM

    Thanks this worked great for me. very simple and easy to understand…
    Just one question is there a way to speed up the translations between slides

  82. Reply Patrick Hughes Feb 5,2015 7:49 AM

    Hi Alan

    Great tutorial and great bit of code it works perfectly thank you very much for this. I searched long and hard to find a way of displaying a slide show of pictures without knowing the pictures names beforehand and encoding them into HTML. Anywhere I went looking for help said it could not be done but then I found your post and it’s perfect.

    Just 2 questions

    Q1. How can I increase the size of the picture box display in your code.

    Q2. Can this code be adapted to play video form a folder local on the server? Once again I have been told on different forms that the only way is by knowing the video name beforehand and encoding it into the player.

    (Example:

    Your browser does not support the video tag.
    )

    The issue is I work in a school and at the front door I have a screen that displays a local run website I am using your picture slider to display pictures and teachers just upload the images to a folder and it all done for them and displayed on the screen.

    My issue is if a teacher wants to display a video they need to deleat the last video that was played on the screen and rename the new video so that my HTML code will display the video on the screen so if there is a way of changing you code to play videos like it dose pictures so the teachers just need to drop in the videos into a local folder that would be great.

    Thanks

  83. Reply jason hirsh Feb 12,2015 11:08 AM

    This is really useful as a real novice in Jquery and PHP. The ability to load a slide show from a file has really streamlined some of my photo web page work… A demo or guide on how to incorporate slide controls would be REALLY great I got half way there borrowing code but not quite there

  84. Reply ryan Feb 18,2015 3:36 PM

    How can I make it pause longer between slides?

  85. Reply Paddy H Sep 13,2015 10:56 AM

    Hi Alan

    Thanks for the code it works great.
    I know the post is old just home your monitoring the replys still
    Is there any way this can be edited to play html5 videos from a folder and not a a picture slideshow

  86. Reply Kev Oct 8,2015 9:19 AM

    Hey I wonder if its possible to make this only look for jpgs in the image folder, I have the problem where .DS_Store files are automatically created any time I open the image folder and the script then tries to display this file as an image, any way to exclude?

  87. Reply nivedha Aug 13,2016 9:43 AM

    can u pls gve me full code

Leave a Reply to Iomoio Cancel Reply

  

  

  

Close Bitnami banner
Bitnami