PHP的scandir功能问题

时间:2018-11-02 09:14:34

标签: php filepath dynamic-arrays scandir

dirdel.php:

<?php
//The name of the folder.
$dir = 'images';
//Get a list of all of the file names in the folder.
$arraydir = scandir($dir, 2);
print_r($arraydir);

//Loop through the file list.
foreach ($arraydir as $key => $value) { 
unlink($arraydir[2]); 
}  
?>

数组输出:

Array ( [0] => . 
        [1] => .. 
        [2] => ana.png 
        [3] => ban.png 
        [4] => ing.png 
        [5] => maca.png 
        [6] => no.png 
        [7] => pret.png )
  

警告:unlink(ana.png):C:\ phpdesktop-中没有此类文件或目录       第10行上的chrome-57.0-rc-php-7.1.3 \ www \ dirdel.php

要调查错误,我还尝试了类似的方法:

require 'images/';

输出:

  

警告:require(C:\ phpdesktop-chrome-57.0-rc-php-7.1.3 \ www \ images):    无法打开流:C:\ phpdesktop-chrome-57.0-rc-中的权限被拒绝    第2行上的php-7.1.3 \ www \ dirdel.php

我要删除由“ $ arraydir [2]”表示的文件“ ana.png”(该文件位于www / images中)

我已经在多个地方搜索过,但是没有找到任何东西可以帮助我解决此问题。

对此有什么解决办法吗?

替代方法有效,只要它们尊重数组的结构即可。

Array ( [0] => . 
        [1] => .. 
        [2] => ana.png 
        [3] => ban.png 
        [4] => ing.png 
        [5] => maca.png 
        [6] => no.png 
        [7] => pret.png )

感谢您的关注。

3 个答案:

答案 0 :(得分:3)

该文件位于images文件夹中,但没有将其添加到unlink()函数参数中。

所以试试这个

unlink($dir . '/' . $arraydir[2]);

答案 1 :(得分:1)

实际上,如果您运行代码,则始终仅取消链接数组的索引2。您必须使用在foreach循环中使用的变量和引用。我建议您尝试以下提到的代码:

<?php
    //The name of the folder.
    $dir = 'images';

    //Get a list of all of the file names in the folder.
    $arraydir = scandir($dir, 2);
    print_r($arraydir);

    //Loop through the file list.
    foreach ($arraydir as $key => $value) {
        if ($arraydir[$key] == 'ana.png' && file_exists($dir . DIRECTORY_SEPARATOR . $arraydir[$key])) {
            unlink($dir . DIRECTORY_SEPARATOR . $arraydir[$key]);
            break;
        } 
    }  
?>

希望这会有所帮助。

答案 2 :(得分:0)

首次尝试删除文件ana.png时,使用的路径是相对于当前目录的,因此找不到该文件。是什么导致了第一个错误。

要解决这个问题,您应该给一个绝对路径名,

$prefix = 'C:\\phpdesktop-chrome-57.0-rc-php-7.1.3\\www\images\\';
$filename = $prefix . $arraydir[2];
unlink($filename)

或,将文件名与其目录名$dir . '/' . $arraydir[2]

连接起来
$dir = 'images'; /*Assuming your current directory is 'C:\phpdesktop-chrome-57.0-rc-php-7.1.3\www\'*/
unlink($dir . $arraydir[2]);

对于第二个错误,似乎您对文件夹“ C:\ phpdesktop-chrome-57.0-rc-php-7.1.3 \ www \ images”没有写权限;您应该更改文件和目录权限。我建议遵循此tutorial关于在Windows 10上设置文件权限