SebastianZdroana
SebastianZdroana

Reputation: 209

how can i return the names of files in a directory using php

lets say I have a folder on a webhost that is called sebis_files and this folder contains some files, maybe pictures, docs...

I want to return the contents of this folder on a separate page, something like:

$row = get dir host/sebis_files*//everything

for ( $row !== 0){ //for every valid file
   echo $row . "<br/>"; //return name of file
}

Upvotes: 0

Views: 959

Answers (3)

Kenney
Kenney

Reputation: 9093

You can use opendir and readdir. Here's a breakdown:

We use __DIR__ to make the path relative to the directory of the current script, just to be safe:

$dir = __DIR__ . '/sebis_files'; 

Next we open the directory to read it's entries. We call readdir, which will return a 'resource' object, or false if $dir is not a readable directory:

if ($dh = opendir($dir))
{

The directory is successfully opened. We now call readdir on that directory. We use the return value of opendir, the mysterious 'resource' object, that will let PHP know what directory we are reading.

Every time we call readdir it will give us the next entry in the directory. When there are no more entries, readdir will return false:

      while ( ($entry = readdir($dh)) !== false)
      {          

We have read a directory $entry: the name of a file or sub-directory inside $dir. So, it's not a full pathname. Let's print it's name, along with whether it is a directory or a file. We will use is_file and is_dir, but we will need to pass the full pathname (hence "$dir/$entry"):

          if ( is_dir( "$dir/$entry" ) )
              echo "Directory: $entry<br/>";
          else if ( is_file( "$dir/entry" ) )
              echo "File: $entry<br/>";
      }

we are done with the directory, let's close it to free the resource:

      closedir($dh);
 }

But what if $dir cannot be opened for reading? Let's print a warning:

 else
     echo "<div class='warning'>cannot open directory!</div>";

Upvotes: 1

mazert
mazert

Reputation: 50

You can do it using the glob function :

$dir = "/your/dir/";

if(file_exists($dir))
{
    foreach (glob("$dir*") as $file) 
    {
        if(is_file($file))
        {
            echo basename($file) . "<br />";
        }
    }
}

Upvotes: 0

Waqar Haider
Waqar Haider

Reputation: 973

you need is to see this

    <?php
$dir = "/tmp";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

sort($files);

print_r($files);

rsort($files);

print_r($files);

?>

Upvotes: 1

Related Questions