doupu1727 2015-11-29 14:21
浏览 45
已采纳

如何使用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
}
  • 写回答

3条回答 默认 最新

  • dtl85148 2015-11-29 14:24
    关注

    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>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?