繁体   English   中英

PHP的scandir函数问题

[英]PHP problems with scandir function

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):第10行的C:\\ phpdesktop-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- php-7.1.3中的权限被拒绝第2行上的\\ 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 )

感谢您的关注。

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

所以试试这个

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

实际上,如果您运行代码,则始终将仅取消链接数组的索引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;
        } 
    }  
?>

希望这可以帮助。

首次尝试删除文件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 . '/' . $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”没有写权限; 您应该更改文件和目录权限。 我建议遵循有关在Windows 10上设置文件权限的本教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM