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

如何使用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条)

报告相同问题?

悬赏问题

  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信