这个问题已经在这里有一个答案:
我想回报多少文件会从我的PHP内通过一个cron任务运行功能删除。
当前的代码如下: -
<?php
function deleteAll($dir) {
$counter = 0;
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) {
deleteAll($file); }
else {
if(is_file($file)){
// check if file older than 14 days
if((time() - filemtime($file)) > (60 * 60 * 24 * 14)) {
$counter = $counter + 1;
unlink($file);
}
}
}
}
}
deleteAll("directory_name");
// Write to log file to confirm completed
$fp = fopen("logthis.txt", "a");
fwrite($fp, $counter." files deleted."."\n");
fclose($fp);
?>
这对我来说很有意义用VBA背景,但柜台返回null我认为,当写在最后我的自定义日志文件。我相信有一些限制,对能够在全球范围内或类似声明的变量共享主机的网站吗?
感谢任何帮助!它不是世界的末日,如果我不能指望被删除的文件,但它会是不错的登录我所选择的格式输出。
这并不工作,由于范围。在您的例子$counter
只存在自己的函数中。
function deleteAll($dir):int {
$counter = 0; // start with zero
/* Some code here */
if(is_dir($file)) {
$counter += deleteAll($file); // also increase with the recursive amount
}
/* Some more code here */
return $counter; // return the counter (at the end of the function
}
$filesRemoved = deleteAll("directory_name");
另外,如果你想发回的详细信息,如“totalCheck”等等,你可以发回信息的数组:
function deleteAll($dir):array {
// All code here
return [
'counter' => $counter,
'totalFiles' => $allFilesCount
];
}
$removalStats = deleteAll("directory_name");
echo $removalStats['counter'].'files removed, total: '.$removalStats['totalFiles'];
还有像“传址参考”其他的解决方案,但你dont want those。