【问题标题】:php scandir() - Invalid argument supplied for foreach() [file]php scandir() - 为 foreach() [文件] 提供的参数无效
【发布时间】:2023-04-10 15:33:01
【问题描述】:

我有一台运行 PHP 版本 5.4.16 的服务器,我正在尝试使用 scandir 列出目录中的文件。我很难弄清楚问题是什么。我已经尝试过 ../store/dir_to_scan 和 /root/store/dir_to_scan。我也尝试过同时使用 glob 和 scandir,正如您在下面看到的那样,都无济于事。如果我删除 dir_to_scan 目录,它将列出 /root/store 中的目录,这是我发现最令人费解的。我还将文件夹和文件更改为 777,以确保这不是权限问题。我在运行时也收到“Array ([type] => 2 [message] => Invalid argument provided for foreach() [file] => /root/html/test.php [line] => 5)”的错误使用正确的目录设置。

感谢您的帮助。

目录设置

/root/html //where php script is run
/root/store/dir_to_scan //files I need to list

PHP 脚本

<?
 #$files = glob('../store/dir_to_scan/*', GLOB_BRACE);
 $files = scandir("/root/store/dir_to_scan/");
   foreach($files as $file) {

      //do work here
      if ($file === '.' || $file === '..') {
                continue;
       }
    echo $file . "<br>";
}
print_r(error_get_last());
?>

【问题讨论】:

    标签: php glob scandir


    【解决方案1】:

    这可能很愚蠢,但请尝试在末尾添加一个斜杠:

    /root/store/dir_to_scan ->

    $files = scandir("/root/store/dir_to_scan/");
    

    【讨论】:

    • 感谢您的回复,不幸的是,无论是否带有斜杠,都存在同样的问题。 ://
    【解决方案2】:

    这应该可以解决您的问题

    $carpeta= "/root/store/dir_to_scan";
        if(is_dir($carpeta)){
            if($dir = opendir($carpeta)){
                while(($file = readdir($dir)) !== false){
                    if($file != '.' && $file != '..' && $file != '.htaccess'){
                      echo $file;  //or save file name in an array..
                     //  $array_file[] = $file;
    
                    }
                }
                closedir($dir);
            }
        }
    

    【讨论】:

    • 是我用来解决这个问题的相同代码,我住在西班牙国家.. $carpeta 是唯一的西班牙语单词
    • 这让我离成功更近了一点。它可以像其他脚本一样读取 /root/store,但不会列出 /root/store/dir_to_scan 中的文件。也就是说,它不再抛出“Array ([type] => 2 [message] => Invalid argument provided for foreach() [file] => /root/html/test.php [line] => 5)”错误.
    • 可能是权限问题,检查一下..也试试这个: echo exec("ls /root/store/dir_to_scan");
    • drwxr-xr-x 2 根 4096 6 月 8 日 09:27 dir_to_scan drwxr-xr-x 2 根 4096 6 月 8 日 07:35 dir_to_scan2 drwxr-xr-x 2 根 4096 6 月 8 日:18 dir_to_scan3 drwxr-xr-x 2 root root 4096 Jun 7 22:18 dir_to_scan4
    • 你用 dir_to_scan2 的函数了吗?你也可以将用户/组的目录和文件更改为 apache。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2023-03-10
    • 1970-01-01
    • 2018-10-06
    • 2013-12-25
    • 1970-01-01
    相关资源
    最近更新 更多