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.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://themeforest.net/user/JeffreyWay Jeffrey Way
    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.

  • http://blog.insicdesigns.com insic

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

  • http://joshmmiller.com Josh

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

  • http://www.freshclickmedia.com Shane

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

  • Gregorio Ramirez

    Awesome time-saver function!

  • http://snedekerdesignz.com/blog/ Craigsnedeker

    Looks awesome!

  • http://instantsolve.net/blog/ Thomas Milburn”

    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);

  • http://www.milesj.me Miles Johnson

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

    http://us3.php.net/glob

  • http://samasmith.com Sam Smith

    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.

  • http://qvister.se Anton Lindqvist

    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]))

  • http://mcarthurgfx.com Sean

    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.

  • http://linkae.com/dmoena dmoena

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

  • Yosy

    Excellent as usual :)
    Thanks allot Jeff :)

  • http://www.themolitor.com THEMOLITOR

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

  • http://laminbarrow.com Lamin

    Great tut Jeff. Thanks

  • http://www.freshivore.net Vince

    @THEMOLITOR

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

  • http://www.eirestudio.net/ Keith

    Thanks Jeffery,

    Fantastic tutorial, thank you. More PHP! :)

  • http://themeforest.net/user/JeffreyWay Jeffrey Way
    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.

  • http://mokshasolutions.com Moksha

    thanks Jeff, was looking for Video Tutorial.

  • http://barttos.net/ Barttos

    @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? :))

  • http://barttos.net/ Barttos

    Jeffrey Way, what you use for generating thumbnails?

  • http://themeforest.net/user/JeffreyWay Jeffrey Way
    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.

  • Jackson

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

  • http://www.blankyao.cn blankyao

    so cool

  • RyanP

    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!

  • TheDoc

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

  • http://www.toosweettobesour.com/ Daniel Cousineau

    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)
    {
    //…
    }

  • http://www.toosweettobesour.com/ Daniel Cousineau

    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

  • http://www.pdxfm.com Mike

    Net toots?

  • http://www.jhaygamba.com/blog/ Jhay

    Looks good. Thanks!

  • http://themeforest.net/user/JeffreyWay Jeffrey Way
    Author

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

  • http://www.islandzilla.com ashvin

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

    keep on with your sweet php tuts man!

  • http://www.aldrinponce.com weblizzer

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

  • yaheed

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

  • http://www.oskard.be jbcarey

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

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

  • http://www.freshclickmedia.com Shane

    @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 :)

  • Hahn

    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.

  • Eduardo

    No coments at all !!

  • Jean-Francois

    Many Thanks Jeff for this great tutorial :)

  • http://61924.wepwnyou.net/ Frank

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

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

  • http://desertlion.net Rijalul Fikri

    Will try this for sure

  • http://tendou86.blogspot.com/ Takumi86

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

  • http://www.estudigital.com Renzo

    Amazing tutorial. Thanks.

  • Sebastian

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

    awesome tut, thx!

  • Terry

    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

  • Pingback: vivanno.com::aggregator » Archive » Scannez les dossiers avec PHP

  • http://www.renderrobot.com Alex

    awesome awesome stuff,

    keep up the good work!

  • http://www.oskard.be jbcarey

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

  • http://www.oskard.be jbcarey

    oh and….

    http://nicof.be/jbcarey/nettuts/ReadFolders/ this is my “result”

  • Pingback: AndySowards.com :: Web Development Nerdy Daily Links For 11/16/2008 | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?