php - 迭代 PHP 文件数组并删除任何没有内容的文件

标签 php

我有一个文件数组,每个文件都有完整的目录路径。我需要迭代我的文件数组,然后删除其中任何 0 字节/非内容的文件。

文件.txt

/lib/Zend/Gdata/App/LoggingHttpClientAdapterSocket.php
/lib/Zend/Gdata/App/Extension.php
/lib/Zend/Gdata/App/MediaEntry.php
/lib/Zend/Gdata/App/FeedEntryParent.php
/lib/Zend/Gdata/App/AuthException.php
/lib/Zend/ProgressBar/Adapter.php
/lib/Zend/ProgressBar/alias.php
/lib/Zend/Locale/code.php
/lib/Zend/Server/Reflection/Function/article.php
/lib/Zend/Server/Reflection/ReturnValue.php
/lib/Zend/Server/Reflection.php
/lib/Zend/Dojo/BuildLayer.php
/lib/Zend/Tag/Cloud/start.php
/lib/Zend/Tag/Cloud/user.php
/lib/Zend/Tag/Item.php
/lib/Zend/Tag/Cloud.php
/lib/Zend/Ldap/Filter/Not.php
/lib/Zend/Ldap/Filter/And.php
/lib/Zend/Ldap/Filter/Exception.php
/lib/Zend/Ldap/Node.php
/lib/Zend/Ldap/Exception.php

PHP

// list of files to download
$lines = file('files.txt');

// Loop through our array of files from the files.txt file
foreach ($lines as $line_num =>$file) {
    echo htmlspecialchars($file) . "<br />\n";

    // delete empty files
}

最佳答案

到目前为止,您的基本循环看起来不错,我认为接下来您会感兴趣的是 filesize()unlink() :

$lines = file('files.txt', FILE_IGNORE_NEW_LINES);

foreach ($lines as $line_num => $file) {
    $file_label = htmlspecialchars($file);
    echo $file_label . "<br />\n";

    if (!file_exists($file)) {
        echo "file " . $file_label . " does not exist<br />\n";
    } else if (filesize($file) === 0) {
        echo "deleting file: " . $file_label . "<br />\n";
        unlink($file);
    }
}

虽然你应该非常小心,以确保它只删除特定目录中的文件,但可能有一个永远不应该删除的文件的白名单,等等。

更新 评论中的一个很好的说明是在 file() 调用中使用 FILE_IGNORE_NEW_LINES 剥离 \r\n 每行返回的字符 =]

关于php - 迭代 PHP 文件数组并删除任何没有内容的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32617295/

相关文章:

php - 在服务器 : How to fix? 上找不到本地主机或 phpMyAdmin

php - { strip } : how to avoid unintended whitespace removal?

php - 而 mysqli_fetch_assoc 在有列而不是行时工作

php - preg_match_all 在使用克拉 (^) 时不匹配

javascript - 无法弄清楚这个 if 语句有什么问题?

javascript - 为什么我的 jQuery Ajax GET 请求没有收到服务器的响应?

php - 从主域为子域设置 cookie

javascript - 我如何在 jquery 的帮助下在 codeigniter 中匹配两个电子邮件地址

PHP构建树形数组/平面数组的面包屑

php - 使用 Ajax 检查按钮是否被点击