Pages

Tuesday, December 4, 2012

Displaying all images in PHP

Ever wonder how to list all images in a directory? The following PHP code will generate a listing of all image files in the current directory as well as the Image MIME Type.

On your php enabled web site, save the code below into a php file and saved it in a public directory which contains your images.

============================
<?php
//*** Copy this file into your image folder under your HTDOCS directory
//***

echo "<style>\n"; echo "<!-- a{text-decoration:none} //-->\n"; echo "</style>\n";

if ($handle = opendir('./')) //*** COMMENT: Opens current directory for reading of filenames
{

    echo "<font face='trebuchet ms' size=1>";
    echo "<b>Image Files</b>:\n";

    echo "<table>"; //*** COMMENT: Header section follows

    echo "<tr>";
    echo "<td bgcolor='#efefef' align='center'>Filename</td>";
    echo "<td bgcolor='#efefef' align='center'>MIME/Image Type</td>";
    echo "<tr>";

    $finfo = finfo_open(FILEINFO_MIME); //*** COMMENT: sets the file information format->MIME

    //*** COMMENT: Details section follows

    while (false !== ($file = readdir($handle)))
    {
    $ftype=strtoupper(finfo_file($finfo, realpath($file)));   //*** COMMENT: Identify file type

    if(stristr($ftype,'IMAGE')) //*** COMMENT: show only IMAGE type files
      {
       $linkname = dirname($file)."/".$file; //*** COMMENT: create a link name we can use in our HTML Anchor tagsg
         
       echo "<tr>";

          echo "<td>";         
            echo "<a href= \"".$linkname."\">"; echo "$file"; echo "</a>"; //*** COMMENT: Display Image Filename
          echo "</td>";

          echo "<td>";  
            echo "  "; echo $ftype; //*** COMMENT: Display Image type
          echo "</td>";        

       echo "<tr>";
      }
    }  
    echo "</table>";
    echo "</font>";
    finfo_close($finfo);

    closedir($handle);
}
?>

==============================


For easy navigation, you can add another code that brings you to the next photo. Web browsers like Internet Explorer and Mozilla Firefox need you to go back to the list. Opera, however, allows you to use the "Forward arrow" to view succeeding photos.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.