首页 > 解决方案 > 如何在 PHP 中删除文件

问题描述

我想删除 PHP 中特定目录中的文件。我怎样才能做到这一点?我有以下代码,但它不会删除文件。

$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
    if ($file != '.' && $file != '..') {
        $files[] = $file;
    }
    unlink($file);
} 

标签: phpfileunlink

解决方案


我认为您的问题并不具体,此代码必须清除目录“文件”中的所有文件。

但是我认为该代码中有一些错误,这是正确的代码:

        $files= array();
        $dir = dir('files');
        while (($file = $dir->read()) !== false) { // You must supply a condition to avoid infinite looping
           if ($file != '.' && $file != '..') {
              $files[] = $file; // In this array you push the valid files in the provided directory, which are not (. , ..) 
           }
           unlink('files/'.$file); // This must remove the file in the queue 
        } 

最后确保您提供了正确的 dir() 路径。


推荐阅读