Find all the files in a directory.

When I find a comic amusing, I grab a screenshot of it. I thought it would be nice to display one comic on my home page each day, so I wrote a little code to look in the comics directory and find all the files, then randomly choose one to display.

There are a few interesting things about the code. First up is scope. Notice that I initialized the two arrays outside of the while loop. That way when I add elements to the arrays, they are not local to the loop. Second, notice that I don’t use an index to add to the arrays. In PHP the preferred way to add an element to an array is with the $arrayName[] notation. Third, I define $location to be the directory handle of the directory. Since I assign it in an if statement, if it fails to find the directory, none of the rest of the code runs. Fourth, I use a similar pattern to read the files in the directory. I read files until there aren’t any more. Finally, I use a flag in my URL so I can proof all of the comics— $all = $_GET[‘all’];.


<?php

$title = array();
$comicsLst = array();

$title = array();
$comicsLst = array();

if ($location = opendir('./Comics')) {

    while (false !== ($entry = readdir($location))) {
   
        if ($entry != "." && $entry != "..") {

            $titleArray = explode(".", $entry);
            $title[] = $titleArray[0];
            $comicsLst[] = $entry;
        }
    }
    closedir($location);
   
    $numComics = count($comicsLst);

    $randomComic = rand(0,$numComics);

    $all  = $_GET['all'];

    if (is_null($all)) {
        echo "<p>";
        echo "<img class='align-left' src='/Comics/$comicsLst[$randomComic]' ";
        echo "alt='$title[$randomComic]' title='$title[$randomComic]' /> ";
        echo "</p>";
        /*
        echo "<p class='attribution'>";
        echo "<a href='index.php?p=Comics&all=y'>Display all comics.</a>";
        echo "</p>";
        */
    } else {

        for($i=0; $i<$numComics; $i++) {
            echo "<p>";
            echo "$title[$i]<br />";
            echo "<img class='align-left' src='/Comics/$comicsLst[$i]' alt='$title[$i]' /> ";
            echo "</p>";
        }
    }
}

I frequently find new comics and add them to my local folder. To keep them synchronized with the server, I wrote a little rsync script.


#!/bin/bash
rsync -a -H -vv -z -l --update --delete --exclude \ Comics --exclude .DS_Store ~wellgolly/Documents/Comics/ \
wellgolly@ wellgolly:/www/WellGolly/Comics/ > \
~ wellgolly/Sites/rsync-backup-comics-`date +%F`.log

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.