简体   繁体   English

如何使用 PHP 从目录中删除所有 .txt 文件

[英]How to Delete ALL .txt files From a Directory using PHP

Im trying to Delete ALL Text files from a directory using a php script.我正在尝试使用 php 脚本从目录中删除所有文本文件。

Here is what I have tried.....这是我尝试过的......

<?php array_map('unlink', glob("/paste/*.txt")); ?>

I dont get an Error when I run this, yet It doesnt do the job.当我运行这个时我没有收到错误,但它并没有完成这项工作。

Is there a snippet for this?有没有这个片段? Im not sure what else to try.我不知道还有什么可以尝试的。

Your Implementation works all you need to do is use Use full PATH您的实现工作您需要做的就是使用Use full PATH

Example例子

$fullPath = __DIR__ . "/test/" ;
array_map('unlink', glob( "$fullPath*.log"))

I expanded the submitted answers a little bit so that you can flexibly and recursively unlink text files located underneath as it's often the case.我稍微扩展了提交的答案,以便您可以灵活地、递归地取消链接位于下面的文本文件,因为这通常是这种情况。

// @param  string  Target directory
// @param  string  Target file extension
// @return boolean True on success, False on failure

function unlink_recursive($dir_name, $ext) {

    // Exit if there's no such directory
    if (!file_exists($dir_name)) {
        return false;
    }

    // Open the target directory
    $dir_handle = dir($dir_name);

    // Take entries in the directory one at a time
    while (false !== ($entry = $dir_handle->read())) {

        if ($entry == '.' || $entry == '..') {
            continue;
        }

        $abs_name = "$dir_name/$entry";

        if (is_file($abs_name) && preg_match("/^.+\.$ext$/", $entry)) {
            if (unlink($abs_name)) {
                continue;
            }
            return false;
        }

        // Recurse on the children if the current entry happens to be a "directory"
        if (is_dir($abs_name) || is_link($abs_name)) {
            unlink_recursive($abs_name, $ext);
        }

    }

    $dir_handle->close();
    return true;

}

You could modify the method below but be careful.您可以修改下面的方法,但要小心。 Make sure you have permissions to delete files.确保您有删除文件的权限。 If all else fails, send an exec command and let linux do it如果一切都失败了,发送一个 exec 命令并让 linux 来做

static function getFiles($directory) {
    $looper = new RecursiveDirectoryIterator($directory);
    foreach (new RecursiveIteratorIterator($looper) as $filename => $cur) {
        $ext = trim($cur->getExtension());
        if($ext=="txt"){
           // remove file: 
        }
    }
    return $out;
}

i have modified submitted answers and made my own version,我修改了提交的答案并制作了我自己的版本,

in which i have made function which will iterate recursively in current directory and its all child level directories,其中我制作了将在当前目录及其所有子级目录中递归迭代的函数,

and it will unlink all the files with extension of .txt or whatever .[extension] you want to remove from all the directories, sub-directories and its all child level directories .它将取消链接所有扩展名为.txt的文件或任何您想要从所有目录、子目录及其所有子级目录中删除的.[extension]文件

i have used : glob() From the php doc:我使用过: glob()来自 php 文档:

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells. glob() 函数根据 libc glob() 函数使用的规则搜索所有匹配模式的路径名,这类似于普通 shell 使用的规则。

i have used GLOB_ONLYDIR flag because it will iterate through only directories , so it will be easier to get only directories and unlink the desired files from that directory.我使用了GLOB_ONLYDIR标志,因为它只会遍历目录,因此只获取目录并从该目录中取消链接所需的文件会更容易。

<?php

//extension of files you want to remove.
$remove_ext = 'txt';
//remove desired extension files in current directory
array_map('unlink', glob("./*.$remove_ext"));

// below function will remove desired extensions files from all the directories recursively.
function removeRecursive($directory, $ext) {

    array_map('unlink', glob("$directory/*.$ext"));

    foreach (glob("$directory/*",GLOB_ONLYDIR) as $dir) {
            removeRecursive($dir, $ext);
    }
    return true;
}

//traverse through all the directories in current directory 
foreach (glob('./*',GLOB_ONLYDIR) as $dir) {
    removeRecursive($dir, $remove_ext);
}

?>

对于任何想知道如何删除(例如:公共目录下的所有 PDF 文件)的人,您可以这样做:

array_map('unlink', glob( public_path('*.pdf')));

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

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