Show all images in folder with PHP

When I work on homepage or mobile layouts, or anything like that, i prefer to first sketch things up on a piece of paper, or in Photoshop. Then after I have a couple of ideas, I take photos of my paper-sketches, make png files of my PSD ideas, and show it all to the client. After receiving feedback I make any changes required, and show everything to the client again. Sometimes it turns out to be a lot of images.

The way I use to show it to the client is by giving them a link to a place where i keep this one PHP file, and a ‘img’ folder where i keep all the images in. The PHP file automatically shows all the images in this folder, and I don’t have to manually update anything, just upload to the folder. You can also use this as a simple photo album with your holiday pictures if you’d like.

UPDATE: Get the latest version of the code below from here.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<title>Show images in folder</title>
<style type="text/css">
body {
    margin: 0 auto 20px;
    padding: 0;
    background: #acacac;
    text-align: center;
}
td {
    padding: 0 0 50px;
    text-align: center;
    font: 9px sans-serif;
}
table {
    width: 100%;
}
img {
    display: block;
    margin: 20px auto 10px;
    max-width: 900px;
    outline: none;
}
img:active {
    max-width: 100%;
}
a:focus {
	outline: none;
}
</style>
</head>
<body>

<?php
$folder = 'img/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$count = count($files);
echo '<table>';
for ($i = 0; $i < $count; $i++) {
    echo '<tr><td>';
    echo '<a name="'.$i.'" href="#'.$i.'"><img src="'.$files[$i].'" /></a>';
    echo substr($files[$i],strlen($folder),strpos($files[$i], '.')-strlen($folder));
    echo '</td></tr>';
}
echo '</table>';
?>

Save the file as index.php, put it in a folder, and then put your images in a sub-folder called ‘img’.
show-images-in-folder - _ml.pe - WinSCP
Here’s a demo (images by John Kenn).

Update:
The above code sorts the images by file name. If you want to sort by file date, change the PHP part to the code as seen below. Please be aware that the date the image have on your server could be the date where you’ve uploaded the image, which is not necessarily the date you’ve created the image.

<?php
$folder = 'img/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$count = count($files);

$sortedArray = array();
for ($i = 0; $i < $count; $i++) {
	$sortedArray[date ('YmdHis', filemtime($files[$i]))] = $files[$i];
}

ksort($sortedArray);
echo '<table>';
foreach ($sortedArray as &$filename) {
	#echo '<br>' . $filename;
	echo '<tr><td>';
    echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>';
    echo substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder));
    echo '</td></tr>';
}
echo '</table>';
?>

Oh, and if you want to have the newest images at the top instead of at the bottom, then change this line:

ksort($sortedArray);

.. to this:

krsort($sortedArray);

48 Thoughts on “Show all images in folder with PHP

  1. leslie on November 16, 2013 at 14:56 said:

    thank you very much been looking everywhere. however do you do video tutorials or could you comment the code to clarify a view things. thank you

    • Mike Lothar on November 16, 2013 at 19:02 said:

      I’ve cleaned up the code a bit now. To clarify, the CSS is basic styling for colours and fonts. Line 23 defines that images should by default not show in wider sizes than 900 pixels. That is overruled in line 27 to show the image at its original size when you click (and hold) the mouse button on the image. Line 37 defines the folder in which you keep your images (relative to the index.php file), and line 38 defines the file types to show, in this case all. Line 43 adds the image, and line 44 adds the name of the file below the image. The complexity of line 44 is because it removes the folder name and the file extension from the name, so that it shows something like ‘john309′ instead of ‘img/john309.jpg’.

      • I see the script shows the file name below the displayed photo. Is there a way to add a specific hyperlink to each photo ….. I was working with line 43 but am stumped on how to add the name of the individual photo file to the url. For instance if the photo file name is lakeside.jpg I would like the url to contain lakeside where I have the XXXXXXXX in the line below.

        ‘;

        So what i would like to end up with is :
        ‘;

        Thank you,
        Brent

      • The post I left earlier for some reason did not show the line 43 code example I was working with so I will explain it here. I would like for each photo to have a specific hyperlink to a url tht contains the photo file name. For instance, if the photo name is 6053011.jpg I would like the href to be http://www.mysite.com/_p/6053011.htm . I sure would apprecite youer help.
        Thank you,
        Brent

  2. keerthana on December 6, 2013 at 09:32 said:

    am a newer to php i execute this code the output is really awesome..
    in there i have a doubt in this line

    echo href line
    i coudnt get it the meaning..
    and dont say its a silly question.pl..
    thanks for help..

  3. Thank you for providing this code. I am hoping there is a way to have a specific hyperlink for each photo displayed. For instance if a photo file name is 56734.jpg , I would like the hyperlink for that photo to be http://www.mysite.com/56734.htm . I worked with the href on line 43 but just am not knowledgeable enough to insert the file name. I sure would appreciate any help you could provide.
    Thank you,
    Brent

  4. Mike Lothar on December 14, 2013 at 17:38 said:

    Hi Brent. Basically you need this line of php code (as seen in line 44):
    substr($files[$i],strlen($folder),strpos($files[$i], '.')-strlen($folder))

    It’ll give you the name of the image with no extension. To explain the php, it consists of the following:
    $files[$i] : gives you the full path, like ‘img/john318.png’
    strlen($folder): gives you how many characters the folder name variable contains, in this example 4, see line 37.
    strpos($files[$i], '.')-strlen($folder): finds the number of characters in the full path before the dot (just before the png), and subtracts the number of how many characters the folder name variable contains.
    All this is surrounded by substr, which is used for splitting up a text, in this case the full path. It takes 3 arguments, the text to split up, where to begin the split, and where to end it. In this case, from the full path of ‘something like ‘img/john318.png’, it will split it to ‘john318′.

    In short, what you need is to use the ‘john318′ part and add the missing code before and after this. So, above line 42, add this line:
    $url = 'http://www.mysite.com/' . substr($files[$i],strlen($folder),strpos($files[$i], '.')-strlen($folder)) . '.htm';

    .. and in line 43, find this:
    href="#'.$i.'"

    .. and replace it with this:
    href="'.$url.'"

  5. Ben Douglas on December 19, 2013 at 01:21 said:

    THANK YOU SO MUCH I DONT NORMALLY COMMENT ON SOMETHING, BUT THIS WAS LIKE A FINAL TOUCH ON MY WEBSITE THAT I HAVE BEEN TRYING TO FIGURE OUT FOREVER.

    THANK YOU

  6. Ben Douglas on December 19, 2013 at 05:21 said:

    Hi, me again, is there any way to sort the images by most recent using the php?
    Thanks

    • Mike Lothar on February 13, 2014 at 22:28 said:

      Hi Ben. Sorry for the late reply.

      Yes there is a way. I’m not a big PHP scripter, but from what I could put together, I’ve made some changes to the script above, so that it now sorts based on the date of the image. Take a look. :)

  7. DINESH on January 11, 2014 at 06:17 said:

    $count=count($files);

    is better i think

    • Mike Lothar on February 13, 2014 at 21:27 said:

      Yes you’re right, there’s no need to call the count() function on each loop. I’ve updated the script. Thanks. :)

  8. chelle on February 3, 2014 at 09:08 said:

    hi.. this tutorial is awesome ! however i would like to ask, if i pull the images out in a folder, how will i put it in a gallery like this http://galleria.io/themes/classic/ ?

    Thanks !
    Chelle

    • Mike Lothar on February 13, 2014 at 22:32 said:

      Hi Chelle.

      This is beyond this scripts capabilities I’m afraid. But I’m convinced you can find a (free) PHP script on the net somewhere to do just this.

      • chelle on February 19, 2014 at 04:52 said:

        i just added the div & script :) simple solution.. :)

        <?php
        $folder = 'file_uploader_laurie/2011/';
        $filetype = '*.*';
        $files = glob($folder.$filetype);
        echo '';
        for ($i=0; $i<count($files); $i++) {
        echo '';
        }
        echo ”;
        ?>

        Galleria.loadTheme(‘galleria/themes/classic/galleria.classic.min.js’);
        Galleria.run(‘.galleria’);

        • chelle on February 19, 2014 at 04:54 said:

          i mean this :)

          <?php
          $folder = 'file/folder/';
          $filetype = '*.*';
          $files = glob($folder.$filetype);

          echo '';
          for ($i=0; $i<count($files); $i++) {
          echo '';
          }
          echo ”;

          ?>

          Galleria.loadTheme(‘galleria/themes/classic/galleria.classic.min.js’);
          Galleria.run(‘.galleria’);

      • chelle on February 19, 2014 at 04:56 said:

        hmm please delete those replies..
        echo ”;
        this line doesn’t seem to appear in my comments >.<

        <?php
        $folder = '2011/';
        $filetype = '*.*';
        $files = glob($folder.$filetype);
        echo '';
        for ($i=0; $i<count($files); $i++) {
        echo '';
        }
        echo ”;
        ?>

  9. Martin on February 10, 2014 at 22:06 said:

    Hello, this is a great script, very helpful indeed. I was wondering if there’s an easy way to sort images by descending name. My knowledge of PHP is limited to say the least, this sounds like something very easy to achieve.

    Thanks again for this wonderful tool!

    • Mike Lothar on February 13, 2014 at 22:42 said:

      Hi Martin.

      I think your knowledge of PHP is not far less than mine. I do know Java though, so it helps me a bit when Googling. :)

      I’ve just added an alternative PHP part to sort the images by date, take a look at this above. Basically, all the images are stored in an array, under what’s called a Key and a Value. The Key for each image is the file date, and the Value is the file name.

      Then, from this page:
      http://www.php.net/manual/en/array.sorting.php

      .. i found out that I needed to use the ksort() method, which sorts the images in the array by its Key (e.g. it’s file date).

      Still with me? Excellent. :) So, for me, it looks like you need to sort the array by the Value (file name), in a high-to-low order. I would almost think the rsort() method is what you need.

      Basically, in my code above, replace this line:

      ksort($sortedArray);

      .. to this:

      rsort($sortedArray);

      Good luck. :)

  10. Gideon Tobi on February 21, 2014 at 01:33 said:

    pls help me, i can’t use this file, i tried removing the spaces in between them, it still didn’t work. Pls anybody who as edited it ans use it can please help me send it to tobicogs1@gmail.com. Plls help me guys.

  11. Hey, thanks a lot! Can you show me how can I put images in two columns? This makes one long column with many rows (for many pictures) :)

    • Nvm, I did it :)

      • Bill on March 7, 2014 at 10:59 said:

        I have the same question – how did you do it?

        • Mike Lothar on March 13, 2014 at 20:35 said:

          The way it is now is that it’s basically a table with one row and one column. You could go the easy way and make two columns, but the more interesting way would be to make it responsive depending on the screen resolution. I might have a go at this one of these days. :)

  12. Hi
    Your code works perfectly for me for my system!

    I do need a bit of help though. I have a script that duplicates all the images from one folder to the another, the time stamp is slightly different but it only pulls in 1 image from each time stamp, and will not display all the images? The script works perfectly if I upload an image one by one. I would be grateful for any help or for you to email me directly as your help would be greatly appreciated!

    • Mike Lothar on March 13, 2014 at 20:48 said:

      I’m not sure i understand this problem. On my server the script isn’t confused about the timestamp, in fact, all the images i’m using have exactly the same timestamp. The php method filemtime() that i’m using shouldn’t be able to go deeper in time than seconds, otherwise we could have used milliseconds to differentiate the images.

  13. Scott on March 6, 2014 at 22:58 said:

    Hello I have tried the original script you posted, yet I can’t seem to get it to work. When I post index.php and have the img folder with the .jpg pictures in the folder, the page just shows blank, no pictures, no errors (the page works, I can change the page attributes like background, etc.). Thanks

    • Mike Lothar on March 13, 2014 at 20:51 said:

      Did you save the file as index.php or default.php? And does your server have php? If not, then i can understand why your page doesn’t show the images.

  14. john on March 8, 2014 at 21:02 said:

    hi i get this error, what is this?

    ‘; for ($i = 0; $i

  15. Robert Briedis on March 15, 2014 at 21:54 said:

    Hello,

    I am trying to get your script to work but its only half working. Its showing me the file names below each image but the images are showing as a “?”. I confirmed with my provider that php is available on my site but I can’t figure it out. Any assistance would be appreciated.

    Thank you.

  16. Hi

    I’m trying to figure out how the script works in order to learn from it, so it would be very helpful for me (and others ? – maybe..) if you made comments to each of the lines (37-48) in the original script in order to clarify how it works.

    I hope you can use my constructive criticism.

    Kind regards,

    Neo

  17. Zartosht Sepideman on May 13, 2014 at 12:26 said:

    Hi
    first of all thanks a lot for giving these code to us,
    second I Have two question:
    1- is ther any way to put css codes in separate file and call it in?? because i tried that and it seams css code in that way doesn’t load.

    2- how can i put jquery code on loaded image, because in neither separate file nor MY JQUERY CODE wont act.

    thanks in advance

  18. rexcel on May 23, 2014 at 06:58 said:

    this is great!!

    how do i display to the images in a table with three columns instead of just 1?

    thanks :)

  19. I have the same problem Daryl has with the timestamp. From multiple images taken the same day, the script only shows one image in it’s output.

  20. Thanks designed for sharing such a nice thought, post is pleasant, thats why i have read it entirely

  21. .table { width:100%; margin-bottom:15px; max-width:1200px; margin:25px auto; display: table; border-collapse: collapse;border-spacing: 0; }
    ::selection {background: #ccc;color: #fff;text-shadow: none;}
    thead{border-bottom:1px solid #444;}
    tfoot{border-top:1px solid #444;}
    table thead,table tbody,table tfoot{text-align:left;text-align:-webkit-left;}

    Table Heading 1
    Table Heading 2
    Table Heading 3

    company[0] AND com[1] AND gif[2] (in array) */
    $domain=trim($var_domain[0]).’.’.trim($var_domain[1]); /* company[0] + com[1] */
    ?>

     
     
    Total : images in

  22. &lt;?php #imges.php
    if(!defined('DS')){ define('DS',DIRECTORY_SEPARATOR); }
    $folder = 'mainbox'.DS;  /* in folder : mainbox/  */
    $filetype = '*.*';  /* example: company.com.gif, logo.com.png, domain.org.jpg .. */
    $files = glob($folder.$filetype);
    $count = 0; /* reset counter */
    $count = count($files); /* do count */
    
    foreach($files as $f){
    	$pics[]=$f; /* create array */
    }
    asort($pics); /* Standard sorting */
    ?&gt;
    &lt;style type=&quot;text/css&quot;&gt;
    .table { width:100%; margin-bottom:15px; max-width:1200px; margin:25px auto; display: table; border-collapse: collapse;border-spacing: 0; }
    ::selection {background: #ccc;color: #fff;text-shadow: none;}
    thead{border-bottom:1px solid #444;}
    tfoot{border-top:1px solid #444;}
    table thead,table tbody,table tfoot{text-align:left;text-align:-webkit-left;}
    &lt;/style&gt;
    
    &lt;center&gt;
    &lt;table class=&quot;table&quot;&gt;
        &lt;caption&gt;&lt;/caption&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;Table Heading 1&lt;/th&gt;
                &lt;th&gt;Table Heading 2&lt;/th&gt;
                &lt;th&gt;Table Heading 3&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
    
    &lt;?php foreach ($pics as &amp;$filename) { 
    	$file=str_replace($folder, '', $filename); /* removes folder-name */
    	$var_domain=explode('.',$file); /* company.com.gif -&gt; company[0] AND com[1] AND gif[2]  (in array) */
    	$domain=trim($var_domain[0]).'.'.trim($var_domain[1]);  /* company[0] + com[1] */
    ?&gt;
    
        &lt;tbody&gt;
            &lt;tr&gt;
                &lt;td&gt;&lt;?php echo $domain;?&gt;&lt;/td&gt;
                &lt;td&gt;&lt;?php echo $file;?&gt;&lt;/td&gt;
                &lt;td&gt;&lt;?php echo $filename;?&gt;&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/tbody&gt;
    
    	&lt;? } ?&gt;
    
        &lt;tfoot&gt;
            &lt;tr&gt;
                &lt;td&gt;&amp;nbsp;&lt;/td&gt;
                &lt;td&gt;&amp;nbsp;&lt;/td&gt;
                &lt;td&gt;Total : &lt;?php echo $count;?&gt; images in &lt;?php echo $folder;?&gt;&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/tfoot&gt;
    
    &lt;/table&gt;
    &lt;/center&gt;
    
  23. Laura on July 16, 2014 at 21:15 said:

    I’ve tweaked this so it’s showing all the images in the subfolders of a folder, but my problem is that it’s also showing the thumbs.db files. is there a way to suppress hidden files, or to have an array of extensions as $filetype? i’ve been poking at it for a while and can’t figure it out.
    Thanks!

  24. Hi,

    am a newer to php i execute this code the output is really awesome..

    Is there possible to Show all images from a different server folder ?
    like that i want to show all images from http://libafoods.com/images/
    in http://arshfood.com/index.php

  25. Dana on August 8, 2014 at 19:02 said:

    I love this code, but am wondering if there is a way to implement pagination?

    • Mike Lothar on August 10, 2014 at 19:51 said:

      I guess it’s possible, but it would make the script quite a bit more complicated. And i’m not that good with PHP honestly.

      If someone figure out a way to do it, i’d be happy to grant them access to push to my Github repository.

  26. Thanks for this, exactly what I need. But why isn’t there a closing body and html tag?

    Looks like you need to add…

  27. Nick on August 27, 2014 at 19:36 said:

    Thank you so much!

  28. Michelle on September 4, 2014 at 21:04 said:

    This was very helpful, however, I am wondering if there is an easy way to sort by category, while also incorporating some kind of jQuery filter plugin.

  29. yajuvendra on September 7, 2014 at 06:40 said:

    Hi Mike,

    me again, is there any way to get the images size or resolution size

    Thanks :)

Leave a Reply

Your email address will not be published. Required fields are marked *


− one = 3

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation