List Files

By Mystery on Feb 20, 2006

This function will grab a list of files/images/etc from a directory and list them as links to that file. Can be very handy, especially with images/image hosts :)

<?php

function list_files($dir)
{
  if(is_dir($dir))
  {
    if($handle = opendir($dir))
    {
      while(($file = readdir($handle)) !== false)
      {
        if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
        {
          echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
        }
      }
      closedir($handle);
    }
  }
}

/*
To use:

<?php

list_files("images/");

?>
*/
?>

Comments

Sign in to comment.
tye   -  Apr 29, 2009

You can use substr to get the portion of the text before the last .

$basefile = substr($file,0,strrpos($file,'.'));

If you add that to the while loop in the above function you can use $basefile to refer to the filename without the extension.

 Respond  
chronix   -  Apr 10, 2009

How could I alter the code so that it doesn't display the file ending (.mp3 etc) and only the name and also the size of the file? I'm quite new to PHP and I can't get my head around the one above.

 Respond  
tye   -  Feb 22, 2006

If you need more than just a list of files, the SPL has a DirectoryIterator object: http://www.php.net/manual/en/function.directoryiterator-construct.php

With it you can do more than just list files, you can also get information about their properties, ownership, permissions, whether or not php can write or read from the file etc.

 Respond  
Hawkee   -  Feb 20, 2006

This will only show files one level deep. If you want it to display everything in the directory tree it will need to be a recursive function.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.