Get $500+ of the best After Effects files, video templates and music for only $20!
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 1 of 21 2
  1. Jeffrey Way says:
    Author

    Are you guys hearing that obnoxious high-pitched hum in the video? Or is it just my laptop? So strange…I may have to reconvert the video and update this posting.

  2. insic says:

    Nice tutorial Jeff. I dont hear the hum youve mentioned. the audio is so clear.

  3. Josh says:

    I hear the high-pitched hum randomly in the background audio, but it’s not that distracting. Thanks for the great tut!

  4. Shane says:

    Hi Jeff! Nope, no hum for me. Thanks for posting the tutorial!

  5. Gregorio Ramirez says:

    Awesome time-saver function!

  6. Just a quick note if you can’t get this to work, scandir is only available in PHP5. If you have PHP4 use:

    $dh = opendir($dir);
    while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
    }
    sort($files);

  7. You could also use glob() to scan a directory… it actually adds more support for getting certain filetypes.

    http://us3.php.net/glob

  8. Sam Smith says:

    What a coincidence, I just did this for a personal project a few weeks ago! I’m part of a team that’s writing a software packing which includes an installable on windows mobile phones. The other team members had been loading the .exe onto an SD card and taking it from phone to phone (about 20 in all) and installing it one at a time.

    Knowing that the phones had wi-fi, I wrote a quick, 25-line PHP script just like this to read the contents of the installer directory and print out links on a webpage. It was MUCH easier to go to the page, click the link, and install than by going one at a time.

  9. Great tutorial!
    You might put somethings similiar to this inside the for-loop so all hidden files while be excluded.

    if(!preg_match(‘/^\./’,$scan[$i]))

  10. Sean says:

    Unless you have a specific need, I find foreach($array as $key => $val) to be far handier.

    Then you can just access $val, and not worry about a counter variable.

    Though it makes little difference.

  11. dmoena says:

    Nice one. I just miss the upload form with automatic thumbnail generation :D otherwise, is a quite useful tool

  12. Yosy says:

    Excellent as usual :)
    Thanks allot Jeff :)

  13. THEMOLITOR says:

    I’d be interested in seeing the auto thumbnail generator you mentioned in the extra creadit ;-)

  14. Lamin says:

    Great tut Jeff. Thanks

  15. Vince says:

    @THEMOLITOR

    The extra credit means: now that you know how to do this. go figure out how to do that.

  16. Keith says:

    Thanks Jeffery,

    Fantastic tutorial, thank you. More PHP! :)

  17. Jeffrey Way says:
    Author

    Yeah – I think I’ll do another screencast that shows how to auto-generate the thumbnails.

    These videos are tough because I want to cover so much, but there just isn’t enough time. Things must be sacrificed.

  18. Moksha says:

    thanks Jeff, was looking for Video Tutorial.

  19. Barttos says:

    @Jeffrey Way, this is a little bug of Camtasia Studio, and a specific version of Adobe Flash Player.

    ps. great tutorial! Next tutorial will be about a protofolio on php and xml? :))

  20. Barttos says:

    Jeffrey Way, what you use for generating thumbnails?

  21. Jeffrey Way says:
    Author

    @Sean – Good point.

    @Barttos – Ahh. thanks.

    @Anton – Nice. I was looking for a regular expression like that. I’m just lazy. :) I’ll be sure to save that expression for future use.

  22. Jackson says:

    Is there a possibilty to cover the same tutorial in ASP.NET with C#. That would be really nice.

  23. RyanP says:

    It’s like you guys knew what I was looking to do. I’ve been working on doing this, but with a flash photo viewer.

    Awesome!

  24. TheDoc says:

    Great stuff Jeff, these types of tutorials are what keep me coming back to NETTUTS. Thanks!

  25. The more commonly accepted method of scanning a directory nowadays is using the SPL’s DirectoryIterator.

    foreach( new DirectoryIterator(‘./’) as $item )
    {
    if( $item->isFile() )
    {
    $item->getFilename(); // file.txt
    $item->getPathname(); // /path/to/file.txt
    }
    elseif( $item->isDot() ) //is . or ..
    { }
    elseif( $item->isDir() )
    { }
    }

    Even more advanced traversals, like scanning all sub directories, can be done with a RecursiveIteratorIterator and RecurisveDirectoryIterator:

    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(‘./’)) as $item)
    {
    //…
    }

  26. Oh, and you can find all the methods you have access to on DirectoryIterator objects from PHP’s website at: http://docs.php.net/directoryiterator

  27. Jhay says:

    Looks good. Thanks!

  28. Jeffrey Way says:
    Author

    @Mike – Yeah, you can say it either way. I use both.

  29. ashvin says:

    thumbnails auto-generation is my nightmare! im waiting for its screencast!

    keep on with your sweet php tuts man!

  30. weblizzer says:

    great tutorial jeff, i’m very much glad you are now venturing into php.. great!

  31. yaheed says:

    Really nice to see the editor of such a great tut website actively posting tutorials himself. Legend!

  32. jbcarey says:

    http://matencafe.maes.be/matencafe/benl/inzendingen

    used this code a few weeks ago on here…. good stuff

  33. Shane says:

    @Jackson – an ASP.NET version would be pretty easy to do. @Jeffrey – I hope you don’t mind me posting C# in a PHP discussion:

    The code below will generate images. Firstly, generate a website, place a Literal control on your page with the ID ‘LiteralImages’, and place this in the page’s Page_Load method:

    if (!Page.IsPostBack)
    {
    // use a string builder to build our output:
    System.Text.StringBuilder outputBuilder = new System.Text.StringBuilder();

    // define the sub-directory:
    string relativeDirectory = “img/”;
    string absoluteDirectory = Server.MapPath( relativeDirectory);

    // get the image files:
    System.IO.FileInfo[] imageFiles =
    new System.IO.DirectoryInfo(absoluteDirectory).GetFiles(“*.jpg”);

    // loop through, building up the output:
    foreach (System.IO.FileInfo currentImage in imageFiles)
    {
    outputBuilder.AppendFormat(
    @”", currentImage.Name,
    relativeDirectory);
    }

    // set the Text property of the literal control
    // (a control that we’ve placed on the ASPX page):
    LiteralImages.Text = outputBuilder.ToString();
    }

    Obviously not as feature rich as Jeffrey’s tutorial, but hopefully enough to get you started. As I write this, I just hope that the code is displayed properly :)

  34. Hahn says:

    i’m really looking forward for your 2nd part of Create a Photo Admin Site Using PHP and jQuery and i hope you can teach and show how to tag and search for the photos too. Also, i hope there would be 2 types of users. One is the administrator and the other is the registered member.

  35. Eduardo says:

    No coments at all !!

  36. Jean-Francois says:

    Many Thanks Jeff for this great tutorial :)

  37. Frank says:

    I made a script/class that scans all images and makes thumbnails too.

    http://61924.wepwnyou.net/projects/imgbrowz0r.html

  38. Will try this for sure

  39. Takumi86 says:

    Great, absolutely great, i’m saving those script for later use, thanks

  40. Renzo says:

    Amazing tutorial. Thanks.

  41. Sebastian says:

    “is slowly getting there, pretty quickly” :-D

    awesome tut, thx!

  42. Terry says:

    How can this error be fixed

    Fatal error: Call to undefined function: scandir() in /home/sites/eireloom.com/public_html/index.php on line 17

    my php versions

    PHP
    4.4.8
    PHP5
    5.2.5

  43. Alex says:

    awesome awesome stuff,

    keep up the good work!

  44. jbcarey says:

    thx for this Mr. Way. Another good script! (although some pagination would have been good too)

  45. Dan Gayle says:

    You could use this same code to “automatically” create navigation for a “dymamic” website that consisted purely of flat file PHP pages. That would be awesome. The ultimate “static” website!

  46. Vikram S. Haer says:

    This is awesome. I worked on a student group website (http://californians.berkeley.edu) and I was thinking of something like this for our newsletter listing. I’m still really new at this stuff and am probably gonna use the concepts shown here to implement an auto-updating list of newsletters. Thanks again jeff! (still waiting on the photo gallery part 2 tho :P)

Comment Page 1 of 21 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.