我的弱共享网络主机不支持 cron 或 perl,我经常需要从某些文件夹中删除数千张 .jpg 图像。图像是从网络摄像头上传的。我想知道是否有一个简单的应用程序可以递归地找到所有 .jpg 图像并删除它们。
我需要能够仅定位以下日期格式的图像:2011-10-19_00-29-06.jpg ...并且只能定位超过 48 小时的图像。
Apache 2.2.20 DirectAdmin 1.39.2 MySQL 5.1.57 Php 5.2.17
我的弱共享网络主机不支持 cron 或 perl,我经常需要从某些文件夹中删除数千张 .jpg 图像。图像是从网络摄像头上传的。我想知道是否有一个简单的应用程序可以递归地找到所有 .jpg 图像并删除它们。
我需要能够仅定位以下日期格式的图像:2011-10-19_00-29-06.jpg ...并且只能定位超过 48 小时的图像。
Apache 2.2.20 DirectAdmin 1.39.2 MySQL 5.1.57 Php 5.2.17
@user427687,您的意思是所有图片格式2011***.jpg
吗?如果是这样,可能我的代码会起作用。
<?php
$path = dirname(__FILE__).'/filepath';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ((time()-filectime($path.'/'.$file)) < 86400*2) {
if (preg_match('/\2011(.*?).jpg$/i', $file)) {
unlink($path.'/'.$file);
}
if (preg_match('/\2011(.*?).jpeg$/i', $file)) {
unlink($path.'/'.$file);
}
}
}
}
?>
或者只是使用 php:
<?php
$last_2_days_in_seconds = 3600 * 48;
foreach (glob("*.jpg") as $filename) {
if((time() - fileatime($filename)) > $last_2_days_in_seconds && preg_match('/^2011/', $filename)) unlink($filename);
}
?>
一个简单的幼稚版本:
$yesterday = date('Y-m-d', strtotime('yesterday')); // 2011-10-17
$day_before = date('Y-m-d', strtotime('2 days ago')); // 2011-10-16
$images = glob('*.jpg');
foreach($images as $img) {
if (strpos($img, $yesterday) === 0) || (strpos($img, $day_before) === 0)) {
continue;
}
unlink($img);
}
这将删除所有带有 3 天或更早日期戳的文件,方法是检查文件是否带有昨天或前一天的日期戳。但它也会删除今天创建的所有文件。
更好的版本是:
$images = glob("*.jpg");
foreach ($images as $img) {
$ctime = filectime($img);
if ($ctime < (time() - 86400 * 2)) {
unlink($img);
}
}
此版本检查文件的实际最后修改时间,并删除超过 48 小时的任何内容。但是,它会更慢,因为 filectime() 执行的 stat() 调用将是一个不便宜的调用。
这样的事情应该让你开始:
class MyRecursiveFilterIterator extends RecursiveFilterIterator {
const EXT = '.jpg';
public function accept() {
// code that checks the extension and the modified date
return $this->current()->getFilename() ...
}
}
$dirItr = new RecursiveDirectoryIterator('/sample/path');
$filterItr = new MyRecursiveFilterIterator($dirItr);
$itr = new RecursiveIteratorIterator($filterItr, RecursiveIteratorIterator::SELF_FIRST);
// to iterate the list
foreach ($itr as $filePath => $fileInfo) {
echo $fileInfo->getFilename() . PHP_EOL;
}