zero-perfoliate
zero-perfoliate

Author Topic: problem with directory listing  (Read 235 times)

Offline topper

  • New PHP Members
  • Posts: 2
  • Karma: +0/-0
problem with directory listing
« on: September 23, 2010, 01:13:46 AM »
Hi everyone.

I'm trying to create a simple directory listing with file type icons.

What I got to so far work preety well with one exception - if file name has more than one dot (.) in it. If file is called "document.doc" it will show file name with appropriate icon "doc.png". But if file is called document.01.doc it will take "01" as file type and display "unknown.png" icon.
To get the file extension i tried first explode using "." as explode marker, then I changed the code to use substr & strrpos, but still with no results.
How do I read the file name from back to make out the file type.
here's my code:

Code: [Select]
$directory=".";
   // handler to the directory
    $dirhandler = opendir($directory);

    // read all the files from directory
    $nofiles=0;
    while ($file = readdir($dirhandler)) {

        // if $file isn't this directory or its parent
        //add to the $files array
        if ($file != '.' && $file != '..')
        {
$nofiles++;
$files[$nofiles]=$file;
        }
    }

   
           foreach ($files as $item)
  {
            $ext = substr($item, strrpos($item, '.') + 1);
                if ($ext=="pdf")
                  $icon = "pdf.png";
                elseif ($ext=="doc")
                  $icon = "doc.png";
                elseif ($ext=="ppt")
                  $icon = "ppt.png";
                elseif ($ext=="xls")
                  $icon = "xls.png";
                elseif ($ext=="txt")
                  $icon = "txt.png";
                else
                  $icon = "unknown.png";
                echo "<img src=\"../images/";
                echo $icon;
                echo " \"/>";
                echo $item;
                echo "<br>";
     
    closedir($dirhandler);

Offline cwarcarblue11

  • PHP Problem Solvers
  • *****
  • Posts: 112
  • Karma: +1/-0
    • C2C Technology
Re: problem with directory listing
« Reply #1 on: September 23, 2010, 09:44:42 AM »
Instead of substr, use this:
Code: [Select]
$exts = split("[/\\.]", $item);
$n = count($exts)-1;
$ext = $exts[$n];

 

zero-perfoliate