Scanning Folders with PHP
videos

Scanning Folders with PHP

Let’s imagine that you want to build a page that will display snapshots of your latest work. One way to do this would be to hard-code the images into your document. The obvious repercussion is that, every time you want to add a new item, you must manually update your html document. Another method would be to store and retrieve the information from a MYSQL database. This will function perfectly, though for many sites, this solution may possibly offer far more power than is technically needed – not to mention the increase in hosting costs.

In such instances, the best solution is to make PHP scan your “portfolio” folder and dynamically create the code for you. If you want to update your page with a new snapshot, all that you need to do is drag the image, and its respective thumbnail, into the appropriate folders – and PHP will do the rest. Let’s build it now!

Portfolio Page

Our Mission

Let’s briefly outline what we need to accomplish.

  • Use PHP to scan our portfolio folder. It will then cyle through each file, that is an image, and then display it on the page.
  • Style our content a bit using CSS.
  • When the users clicks on a thumbnail, we’ll use jQuery to load the large version of the image in the main panel.
  • If the user has Javascript disabled, he’ll simply be directed to a new page that contains the full-sized image

How to Use It

Adding a new image to our portfolio is simple. Take a snapshot of your website, brochure, postcard, etc and size it to 500px x 350px. Place this image within the “images/featured” folder.

Next, create a thumbnail that is 50px x 50px. Place this image within the “images/tn” folder.

You must make sure that both the full-sized and the thumbnail images have the exact same file name.

Our Final HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Scanning Directories with PHP</title>
    <script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
    <script src="js/scripts.js" type="text/javascript"></script>
    <link href="default.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div id="container">
	<h1>Some Portfolio</h1>
        <div id="featured">
			<?php
				$featured_dir = 'images/featured/';
				$scan = scandir($featured_dir);
				echo '<img src="'. $featured_dir . $scan[2] . '" alt="image" />';
			?>
        </div>

        <ul id="options">
		<?php
			$dir = 'images/tn/';
			$scan = scandir($dir);

			for ($i=0; $i<count($scan); $i++) {
			 if ($scan[$i] != '.' && $scan[$i] != '..') {
			 echo '
			 <li>
			  <a href="' . $featured_dir . $scan[$i] . '">
			   <img src="'. $dir . $scan[$i] . '" alt="'. $scan[$i] . '" />
			  </a>
			 </li>';
			 }
			}
		?>
        </ul>
    </div>
</body>
</html>

Our Final CSS

View it here.

Compensating For IE6

IE6 Problem

Luckily, we only have one thing to fix. If you look at the image above, you’ll see that the #options unordered list is not containing its floated list items. While modern browsers will correctly clear the items thanks to our “overflow: hidden;” style, IE6 needs one more rule. Append this to your stylesheet.

ul#options {
...misc styles...
height: 1%;
}

I could have set the height to anything and it would still work. Think of it as Drago punching IE6 in the face and telling it, “Wake up!”. This style forces IE6 to expand as much as is need to clear its children.

The Complete Javascript(jQuery)

$(function() {
    $.preloadImage = function(path) {
        $("#featured img").attr("src", path);
    }

    $('ul#options li img').click(function() {
        $('ul li img').removeClass('selected');
        $(this).addClass('selected'); 							    

        var imageName = $(this).attr('alt'); 					    

       $.preloadImage('images/featured/' + imageName);

        var chopped = imageName.split('.');
        $('#featured h2').remove();
        $('#featured')
		 .prepend('

' + chopped[0] + '

').children('h2').fadeIn(500).fadeTo(200, .6); }); $('ul#options li a').click(function() { return false; }); });

Extra Credit

There are ways to create thumbnails of our images dynamically. Try to find a way to make PHP scan our “featured” folder and then dynamically create a thumbnail version and save it within the “tn” folder.

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Add Comment

Discussion 72 Comments

Comment Page 2 of 2 1 2
  1. Vikram S. Haer says:

    One question: If we were working with a list of files (pdfs in my case) and wanted to sort them a specific way, is there any way we could do so? For me, I wanted to sort the list by date since I want most recent newsletters to appear at the top. Any help would be appreciated.

    http://californians.berkeley.edu I noticed the link didn’t work above so thought i’d try retyping it without the parens.

  2. iexx says:

    In additional You can add a Exif PHP functions for getting Image exif information

  3. Alex says:

    2Jeffrey Way
    Thnx, but…
    If 500 images in folder…?
    May be create listing (1 page = 50 pics)
    We want see video “How get listing ?” :)

  4. Sean says:

    Hey, a question, how would it be possible to have a button go to the next image in the list?

  5. tisodotsk says:

    Great tutorial for beginers, but with programmatical mistakes in PHP:
    - better than scandir() (witch returns folders and files) is work with files only – glob() or some user function can do that.

    - foreach($scan as $val) is better than for($i=0;$i<count($scan);$i++), you don’t need to now how many files are there, you only need process all of them.

  6. Jetoine says:

    I’m almost a total NOOB! how can I modify this code to say scan a text based html filesystem and create dynamic links.

    I have a number of growing folders that contain html stories and I need a way to organize them.

    a modification of this code could work for an index system right?

  7. Terminal says:

    I use this bit of code instead, this way I don’t have to make a thumbnail. I use it to display wallpapers I make. Since I don’t know RegEx, this is the best way for me:

    <?php

    function getFileDetails($dir)
    {
    $files = array();
    $allowed = array(‘jpg’, ‘gif’, ‘png’);
    $i = 0;

    if ( ($h = opendir($dir)) == false )
    {
    die(‘Error: Could not open directory.’);
    }

    while ( false !== ($file = readdir($h)) )
    {
    $parts = explode(‘.’, $file);
    $cnt = count($parts)-1;
    $ext = $parts[$cnt];

    if ( in_array($ext, $allowed) == true )
    {
    $files[$i]['filename'] = $parts[0];
    $files[$i]['filelink'] = $dir.$file;
    $dimensions = getimagesize($dir.$file);
    $files[$i]['filedim'] = $dimensions[0].’ x ‘.$dimensions[1];
    $kb = number_format(filesize($dir.$file)/1024, 0, ”, ”).’ kb’;
    $mb = number_format($kb/1024, 2, ‘.’, ”).’ mb’;
    $files[$i]['filesize'] = $kb.’ (‘.$mb.’)';
    $files[$i]['filetype'] = ( $ext == ‘jpg’ ) ? strtoupper(‘jpeg’) : strtoupper($ext);
    $i++;
    }

    }

    $h = closedir($h);
    return $files;
    }

    function FileDetailsList($dir)
    {
    $files = getFileDetails($dir);
    $list = ”;

    for ( $i = 0; $i < count($files); $i++ )
    {
    $thumbsrc = ‘data:image/jpeg;base64,’.base64_encode(exif_thumbnail($files[$i]['filelink']));

    $list .= ‘‘.$files[$i]['filename'].’‘;
    $list .= ”;
    $list .= ‘Preview: ‘;
    $list .= ‘Screen Resolution: ‘.$files[$i]['filedim'].”;
    $list .= ‘Filesize: ‘.$files[$i]['filesize'].”;
    $list .= ‘Image Type: ‘.$files[$i]['filetype'].”;
    $list .= ”;
    $list .= ”;
    }

    $list .= ”;
    return $list;
    }

    ?>

  8. Terminal says:

    That last function should be this, sorry!

    function FileDetailsList($dir)
    {
    $files = getFileDetails($dir);
    $list = ‘<ul>’;

    for ( $i = 0; $i Preview:</span> <a href=”‘.$files[$i]['filelink'].’”><img src=”‘.$thumbsrc.’” /></a></li>’;
    $list .= ‘<li><span>Screen Resolution:</span> ‘.$files[$i]['filedim'].’</li>’;
    $list .= ‘<li><span>Filesize:</span> ‘.$files[$i]['filesize'].’</li>’;
    $list .= ‘<li><span>Image Type:</span> ‘.$files[$i]['filetype'].’</li>’;
    $list .= ‘</ul>’;
    $list .= ‘</li>’;
    }

    $list .= ‘</ul>’;
    return $list;
    }

  9. Terminal says:

    i need a preview comment button! anyways, this was the import part of the 2nd function:

    $thumbsrc = ‘data:image/jpeg;base64,’.base64_encode(exif_thumbnail($files[$i]['filelink']));

    although when rendered, the source is HUGE

  10. Ryan Edick says:

    This is a great tutorial and exactly what I need for a project of mine!

    I am wondering though, in the if statement you said you could exclude certain file types, is there is a way to exclude an entire file?

    I have a file within the directory I am scanning and it is being added to the array. If anyone can help me to add the exception to the if statement that would help me a ton!

    thanks!

  11. Johan says:

    It’s a great tutorial but is it possible to do this with .flv’s, or any other type of video file? I want it to create a text-link (instead of the thumbnail) that opens the .flv where the full-size pic is. i have tried my best but im not that good at php and scripts yet.

  12. crawford13 says:

    i am a beginner with php, actually i really don’t know it at all, but this what i have been looking for. but is there a way to have the thumbnails open up with lightbox rather than display the larger image above the thumbnails the way they do in the demo?

  13. Brent says:

    This would be the perfect script if you didn’t still have to create thumbnails for it. It’s fine if you have a couple of images, but a large gallery would be a pain.

  14. David Moreen says:

    Oh Jeffrey you never cease to impress. This is exactly what I was looking for.

  15. abhishek says:

    Thanks..
    i took me a little while to figure out the error in my code but this really works

  16. Rob says:

    Great tutorial. Is it possible to has a search function that will allow a user to search for a specific file name?

  17. rs says:

    Thanks..Wonderful tutorial !!

  18. lnorby says:

    A shorter solution for displaying thumb images:

    $dir=’images/tn’;
    $scan=array_slice(scandir($dir),2);

    foreach ($scan as $image)
    {
    echo “\n”;
    }

  19. Dolido says:

    Thanks for this great tuts.

  20. Scott says:

    Great tutorial! I’m just starting to redo 2.0 of my website and this came in handy! One question….what do you change in the PHP code to allow for multiple galleries on a single HTML page. Tried just copy and pasting the first gallery in the index.php page but as soon as I add the second gallery, the functionality dies. The larger images open up in a new window. Do I simply change the for each new gallery (ie; div id=”gallery1″ , div id=”gallery2″ and so on and so forth)? Any help would be greatly appreciated!

  21. Donald says:

    Would it be possible to populate the contents, which in my case would be .html files, of a jQuery accordion using your method?
    Thank you. The tutorial is great!

Comment Page 2 of 2 1 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.