List only some extention (File Listing)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Peuplarchie
Forum Contributor
Posts: 148
Joined: Sat Feb 04, 2006 10:49 pm

List only some extention (File Listing)

Post by Peuplarchie »

Good day to you all,
I'm working on a pice of code which list all files in a directory and return the list and its content right under the name of the file.

Code: Select all

 
 
<?php
$thelist = "";
 if ($handle = opendir('.')) {
   while (false !== ($file = readdir($handle)))
      {
          if ($file != "." && $file != "..")
      {
            $thelist .= '<a href="'.$file.'">'.$file.'</a><br/>';
            $contents = file($file);
            $string = implode($contents);
            $thelist .= '<p>'.$string.'</p>';
            
          }
       }
  closedir($handle);
  }
?>
<P>List of files:</p>
<P><?=$thelist?></p>
 
 

I'm looking for a way of choose only 3 or 4 extension only.

How would I dow so ?

Thanks !
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: List only some extention (File Listing)

Post by novice4eva »

Code: Select all

 
$myExt = array('php','dat','txt');
while (false !== ($file = readdir($handle)))
{
$fileChunks = array_reverse(explode(".", $file));
$ext= $fileChunks[0];
if ($file != "." && $file != ".." && in_array($ext,$myExt))
{
 .....
......
}
}
 
mmj
Forum Contributor
Posts: 118
Joined: Fri Oct 31, 2008 4:00 pm

Re: List only some extention (File Listing)

Post by mmj »

@novice4eva, its a good idea to lower case the extension, just in case.

also I prefer to use string functions, they are usually faster then array functions.

@op, whats the point of putting the file into an array if you just want to implode it afterwards?

Code: Select all

if ($file == '.' || $file == '..' || !in_array(strtolower(substr($file, strrpos($file, '.') + 1)), $exts))
    continue;
$thelist .= '<a href="'.$file.'">'.$file.'</a><br/>';
$string = file_get_contents($file);
$thelist .= '<p>'.$string.'</p>';
Post Reply