我有一个文件数组,每个文件都有完整的目录路径。我需要迭代我的文件数组,然后删除其中一个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
字符=]
有两个函数可以执行此操作,一个是filesize()
,用于检查文件的大小,另一个是file_exists()
,用于检查是否存在文件。要删除文件,请使用unlink()
函数。
foreach ($lines as $line_num =>$file) {
if(file_exists($file) && filesize($file) === 0) {
unlink($file);
}
}