Auto Image Display With PHP And JQuery

This script will automatically display all the .jpg images in a given folder. The beauty of this script is that it needs no database access. The information for the caption (and alt) are in the images themselves. Easy modifications that might be nice (but have not been implemented here):

  • display the images randomly
  • limit the number of images to be displayed
  • use .htacess to rewrite the url (hide ‘fldr= …’)

A working example can be seen here: Auto Image Display With PHP And JQuery Example

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title>Auto Image Display</title>
        <style type="text/css">
            #imgShow {
                position: relative;
                margin: 50px auto;
                width:800px;
                height:680px;
                padding: 10px;
                box-shadow: 0 0 20px rgba(0,0,0,0.4);
            }
            #imgShow > div {
                position: absolute;
                top: 10px;
                left: 10px;
                text-align: center;
            }
            #imgShow div img {
                border:1px solid #555;
                width: 800px;
            }
        </style>
        <script src="scripts/jquery-1.8.3.min.js"></script>
        <script>
            $(function() {
                $("#imgShow > div:gt(0)").hide();
                setInterval(function() {
                    $('#imgShow > div:first')
                            .fadeOut(1000)
                            .next()
                            .fadeIn(1000)
                            .end()
                            .appendTo('#imgShow');
                }, 5000);
            });
        </script>
    </head>
    <body>
        <?php
        /**
         * autoImageDisplay.php
         * automatically display photos in a folder
         * @author Robert Newton <lektrikpukeAtYahooDotCom>
         * if you use/reuse my code, please give a mention to my site/blog--Thanks!
         * 
         * Overview:
         * 
         * get folder
         * iterate through files
         * look for JPEGs (could use filetype as a toggle for where to get alt and caption data)
         * using exif, retrieve image type, and ImageDescription, to be used for alt and caption
         * 
         */
        $pics = array();

        /**
         * exifImageType
         * checks if image is a jpg
         * @param string $pathway
         * @param string $v
         * @return boolean
         */
        function exifImageType($pathway, $v) {
            if (exif_imagetype($pathway . $v) != IMAGETYPE_JPEG) {
                return FALSE;
            }
            return TRUE;
        }

        /**
         * readExif
         * reads exif data and returns image description if present
         * @param string $pathway
         * @param string $val
         * @return string
         */
        function readExif($pathway, $val) {
            $exif = exif_read_data($pathway . $val); // read EXIF headers
            // Note:  $exif['ImageDescription'] translates to an image's properties >> details (tab) >> Title (under description section) in Windows
            // If there is no text in ImageDescription, there will be no index (key), so check if it exists (no need to check if blank)
            $altCaption = array_key_exists('ImageDescription', $exif) ? $exif['ImageDescription'] : 'No Description';
            return $altCaption;
        }

        if (isset($_GET['fldr']) && ctype_alnum($_GET['fldr'])) {
            $pathway = "images/slideshow/{$_GET['fldr']}/";
            try {
                if (!is_dir($pathway)) {
                    throw new Exception('That folder does not exist!');
                }
                else { // else it is a folder
                    if ($dh = opendir($pathway)) {
                        while (($files[] = readdir($dh)) !== false) {
                            // read all files in folder (directory) into array
                        }
                        if (count($files) > 0) {
                            foreach ($files as $v) {
                                if (preg_match("/.\.jpg/i", $v) && filesize($pathway . $v) > 11) { // file must be at least 12 bytes in size (or read error), hence greater than 11.  
                                    // REF:  https://php.net/manual/fa/function.exif-imagetype.php
                                    if (!exifImageType($pathway, $v)) { // call to function so it's easier to replace if you decide to not use exif
                                        throw new Exception('File: ' . $v . ' is not a valid jpg image!');
                                    }
                                    else { // reasonably sure it's a picture, so add it to pics array
                                        $pics[] = $v;
                                    }
                                } // end if preg_match && filesize
                            } // end foreach
                        } // end if count file > 0 -- no need for an else here because it'll be picked up by $pics below
                        if (count($pics) > 0) { // check to see if there is at least one jpg in array
                            sort($pics); // sort images alphabetically, but could put randomize here
                            $slideShow = '<div id="imgShow">';
                            foreach ($pics as $key => $val) {
                                $altCaption = readExif($pathway, $val); // call to function so it's easier to replace if you decide to not use exif
                                $slideShow .= '
            <div>
                <img src="' . $pathway . $val . '" alt="' . $altCaption . '" /><br />
                <p>' . $altCaption . '</p>
            </div>';
                            } // end foreach
                            $slideShow .= '
        </div>' . "\n";
                            echo $slideShow;
                        } // end if count pics > 0
                        else {
                            throw new Exception('There are no images in that folder!');
                        }
                    } // end if can open dir
                    else {
                        throw new Exception('Could not open that folder!');
                    }
                } // end if is dir
            } // end try
            catch (Exception $e) { // display error messages that were caught
                echo $e->getMessage();
            }
        }
        else {
            echo 'Nothing to display';
        }
        ?>
    </body>
</html>

The comments are plentiful and hopefully self-explanatory. Script is for entertainment and educational purposes only.

Suggestions for use:

  • Lock down folders on server to secure private data
  • Limit the number of images in each folder
  • Too many images, or images that are too large, will take a long time to download and ruin the user’s experience
  • Change parameters (folder location, pathway, jquery timing, css) to match your site requirements
This entry was posted in Computer Stuff, PHP and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

Enter Captcha Here : *

Reload Image