簡體   English   中英

使用PHP從文件夾中刪除所有文件?

[英]Deleting all files from a folder using PHP?

例如,我有一個名為“Temp”的文件夾,我想使用 PHP 從該文件夾中刪除或刷新所有文件。 我可以這樣做嗎?

$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file)) {
    unlink($file); // delete file
  }
}

如果要刪除 .htaccess 等“隱藏”文件,則必須使用

$files = glob('path/to/temp/{,.}*', GLOB_BRACE);

如果要刪除文件夾(包括子文件夾)中的所有內容,請使用array_mapunlinkglob組合:

array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );

此調用還可以處理空目錄(感謝您的提示,@mojuba!)

這是使用標准 PHP 庫 (SPL)的更現代的方法。

$dir = "path/to/directory";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
    $file->isDir() ?  rmdir($file) : unlink($file);
}
return true;
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}

此代碼來自http://php.net/unlink

/**
 * Delete a file or recursively delete a directory
 *
 * @param string $str Path to file or directory
 */
function recursiveDelete($str) {
    if (is_file($str)) {
        return @unlink($str);
    }
    elseif (is_dir($str)) {
        $scan = glob(rtrim($str,'/').'/*');
        foreach($scan as $index=>$path) {
            recursiveDelete($path);
        }
        return @rmdir($str);
    }
}
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
    unlink($v);
}

假設你有一個文件夾,里面有很多文件,讀取它們,然后分兩步刪除,效果並不好。 我相信刪除文件最有效的方法是使用系統命令。

例如在 linux 上我使用:

exec('rm -f '. $absolutePathToFolder .'*');

或者如果你想遞歸刪除而不需要編寫遞歸函數

exec('rm -f -r '. $absolutePathToFolder .'*');

PHP 支持的任何操作系統都存在相同的命令。 請記住,這是一種刪除文件的 PERFORMING 方式。 在運行此代碼之前必須檢查並保護 $absolutePathToFolder 並且必須授予權限。

請參閱readdirunlink

<?php
    if ($handle = opendir('/path/to/files'))
    {
        echo "Directory handle: $handle\n";
        echo "Files:\n";

        while (false !== ($file = readdir($handle)))
        {
            if( is_file($file) )
            {
                unlink($file);
            }
        }
        closedir($handle);
    }
?>

從 PHP 文件夾中刪除所有文件的簡單和最佳方法

$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
    if(is_file($file))
    unlink($file); //delete file
}

從這里得到這個源代碼 - http://www.codexworld.com/delete-all-files-from-folder-using-php/

unlinkr 函數通過確保它不會刪除腳本本身來遞歸刪除給定路徑中的所有文件夾和文件。

function unlinkr($dir, $pattern = "*") {
    // find all files and folders matching pattern
    $files = glob($dir . "/$pattern"); 

    //interate thorugh the files and folders
    foreach($files as $file){ 
    //if it is a directory then re-call unlinkr function to delete files inside this directory     
        if (is_dir($file) and !in_array($file, array('..', '.')))  {
            echo "<p>opening directory $file </p>";
            unlinkr($file, $pattern);
            //remove the directory itself
            echo "<p> deleting directory $file </p>";
            rmdir($file);
        } else if(is_file($file) and ($file != __FILE__)) {
            // make sure you don't delete the current script
            echo "<p>deleting file $file </p>";
            unlink($file); 
        }
    }
}

如果要刪除放置此腳本的所有文件和文件夾,請按如下方式調用它

//get current working directory
$dir = getcwd();
unlinkr($dir);

如果您只想刪除 php 文件,請按如下方式調用它

unlinkr($dir, "*.php");

您也可以使用任何其他路徑來刪除文件

unlinkr("/home/user/temp");

這將刪除 home/user/temp 目錄中的所有文件。

另一種解決方案:此類刪除所有文件、子目錄和子目錄中的文件。

class Your_Class_Name {
    /**
     * @see http://php.net/manual/de/function.array-map.php
     * @see http://www.php.net/manual/en/function.rmdir.php 
     * @see http://www.php.net/manual/en/function.glob.php
     * @see http://php.net/manual/de/function.unlink.php
     * @param string $path
     */
    public function delete($path) {
        if (is_dir($path)) {
            array_map(function($value) {
                $this->delete($value);
                rmdir($value);
            },glob($path . '/*', GLOB_ONLYDIR));
            array_map('unlink', glob($path."/*"));
        }
    }
}

發布了一個通用的文件和文件夾處理類,用於復制、移動、刪除、計算大小等,可以處理單個文件或一組文件夾。

https://gist.github.com/4689551

使用:

復制(或移動)單個文件或一組文件夾/文件:

$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');

刪除路徑中的單個文件或所有文件和文件夾:

$files = new Files();
$results = $files->delete('source/folder/optional-file.name');

計算單個文件或一組文件夾中的一組文件的大小:

$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');
 <?
//delete all files from folder  & sub folders
function listFolderFiles($dir)
{
    $ffs = scandir($dir);
    echo '<ol>';
    foreach ($ffs as $ff) {
        if ($ff != '.' && $ff != '..') {
            if (file_exists("$dir/$ff")) {
                unlink("$dir/$ff");
            }
            echo '<li>' . $ff;
            if (is_dir($dir . '/' . $ff)) {
                listFolderFiles($dir . '/' . $ff);
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}
$arr = array(
    "folder1",
    "folder2"
);
for ($x = 0; $x < count($arr); $x++) {
    $mm = $arr[$x];
    listFolderFiles($mm);
}
//end
?> 

對我來說,使用readdir的解決方案是最好的,而且效果很好。 使用glob ,該功能在某些情況下失敗。

// Remove a directory recursively
function removeDirectory($dirPath) {
    if (! is_dir($dirPath)) {
        return false;
    }

    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }

    if ($handle = opendir($dirPath)) {

        while (false !== ($sub = readdir($handle))) {
            if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
                $file = $dirPath . $sub;

                if (is_dir($file)) {
                    removeDirectory($file);
                } else {
                    unlink($file);
                }
            }
        }

        closedir($handle);
    }

    rmdir($dirPath);
}
public static function recursiveDelete($dir)
{
    foreach (new \DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {
            if ($fileInfo->isDir()) {
                recursiveDelete($fileInfo->getPathname());
            } else {
                unlink($fileInfo->getPathname());
            }
        }
    }
    rmdir($dir);
}

我已經構建了一個非常簡單的包,稱為“Pusheh”。 使用它,您可以清除目錄或完全刪除目錄( Github 鏈接)。 它也可以在Packagist找到

例如,如果要清除Temp目錄,可以執行以下操作:

Pusheh::clearDir("Temp");

// Or you can remove the directory completely
Pusheh::removeDirRecursively("Temp");

如果您有興趣,請參閱wiki

我更新了@Stichoza 的答案以通過子文件夾刪除文件。

function glob_recursive($pattern, $flags = 0) {
    $fileList = glob($pattern, $flags);
    foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
        $subPattern = $dir.'/'.basename($pattern);
        $subFileList = glob_recursive($subPattern, $flags);
        $fileList = array_merge($fileList, $subFileList);
    }
    return $fileList;
}

function glob_recursive_unlink($pattern, $flags = 0) {
    array_map('unlink', glob_recursive($pattern, $flags));
}

這是一個簡單的方法和很好的解決方案。 試試這個代碼。

array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM