【问题标题】:Lstat error for filetype(). Followed example from php.net文件类型()的 Lstat 错误。来自 php.net 的示例
【发布时间】:2015-12-02 11:15:45
【问题描述】:

我正在尝试从文件中获取目录数据。

期望的行为我希望代码回显目录。我最终会将它们全部放入一个数组中。

问题我收到几个警告:filetype(): Lstat failed 错误。所有这些都在 WAMP 上进行了测试。

这是我的代码:

    $dir = "../images/";


echo $dir;

if (is_dir($dir)){
   if ($dh = opendir($dir)){
        while ($file = readdir($dh) !== false){
            echo "filename: $file : filetype: ". filetype($dir . $file). "</br>";
        }
    closedir($dr);

        }
}

任何帮助将不胜感激。

【问题讨论】:

  • 我不确定你的意思。你能澄清一下吗?

标签: php arrays loops


【解决方案1】:

不要忘记最先出现的 ...。测试它们。

<?php
....
if (is_dir($dir)){
  $dh=opendir($dir);
  while ($file = readdir ($dir)) {
    if ($file != "." && $file != "..") {
        echo "filename: $file : filetype: ". filetype($dir . $file)."</br>";
    }
  }
  closedir($dh);
}
?>

更新

要测试脚本,请将其放在文件夹 images 的上一层,然后试试这个:

<?php
chdir ('images');
$dh=opendir('.');
while ($file = readdir ($dh)) {
   if ($file != "." && $file != "..") {
        echo "filename: $file : filetype: ". filetype($file)."</br>";
    }
}
  closedir($dh);
?>

问题

为什么要使用if ($file != "." &amp;&amp; $file != "..") {

readdir() show also if there are above levels of the directory

所以你得到的第一个 readdir()

  • 1.) '.'
  • 2.) '..'
  • 3.) afile.jpg

【讨论】:

  • 所以我已经按照您的代码进行了修复。关闭($dh);但现在什么都没有弹出。我猜它不会通过。为什么不是?
  • @JPFoster :我的代码应该只显示您必须放置 if() 语句的位置。仅将 if($file != "."...) { your code } 放入初始代码中。
  • 我不确定我是否跟随。 “最好将脚本放在上一层然后”是什么意思?我试图将目录移动到 /images 以确保目录正确且没有输出(并且文件夹中有图片文件)。我还没有尝试过 chdir 功能。我会把第二段代码放在哪里?在第一个 if 语句之前?
  • 哦等等!我更改了代码,它可以工作。它回显目录。非常感谢!原来我没有注意到你的 while 语句发生了变化。 $file != ".." 做什么?或 $file != "."。为什么我需要那个?
  • @JPFoster:请看我的更新Why to use ..
猜你喜欢
  • 1970-01-01
  • 2011-10-14
  • 2021-05-04
  • 1970-01-01
  • 2014-08-26
  • 2021-08-21
  • 2020-09-08
  • 2017-04-25
  • 2014-05-13
相关资源
最近更新 更多