Php 删除文件夹中的一些文件
我有一个cronjob,每天都会删除所有未使用的文件,但我希望能更进一步。我的文件是这种结构的Php 删除文件夹中的一些文件,php,Php,我有一个cronjob,每天都会删除所有未使用的文件,但我希望能更进一步。我的文件是这种结构的name\u number.jpg,但有些文件是这种结构的name\u.jpg 目前,我的脚本没有任何区别,并且删除了所有内容。我希望脚本删除name\u number.jpg,而不删除没有编号的文件 $days = 1; $path = './result/'; // Open the directory if ($handle = opendir($path)) { /
name\u number.jpg
,但有些文件是这种结构的name\u.jpg
目前,我的脚本没有任何区别,并且删除了所有内容。我希望脚本删除name\u number.jpg
,而不删除没有编号的文件
$days = 1;
$path = './result/';
// Open the directory
if ($handle = opendir($path))
{
// Loop through the directory
while (false !== ($file = readdir($handle)))
{
// Check the file we're doing is actually a file
if (is_file($path.$file))
{
// Check if the file is older than X days old
if (filemtime($path.$file) < ( time() - ( $days * 24 * 60 * 60 ) ) )
{
// Do the deletion
unlink($path.$file);
}
}
}
}
$days=1;
$path='./result/';
//打开目录
如果($handle=opendir($path))
{
//循环浏览目录
while(false!=($file=readdir($handle)))
{
//检查我们正在做的文件实际上是一个文件
if(is_文件($path.$file))
{
//检查文件是否早于X天
如果(filemtime($path.$file)<(time()-($days*24*60*60)))
{
//执行删除操作
取消链接($path.$file);
}
}
}
}
提前感谢您的回复。使用迭代器:
$days = 1;
$fsi = new RegexIterator(
new FilesystemIterator('/path/to/your/files'),
'(.+_\d+\.jpg$)'
);
/** @var SplFileObject $file */
foreach ($fsi as $file) {
if ($file->isFile() && $file->getMTime() < strtotime("-$days day")) {
unlink($file);
}
}
$days=1;
$fsi=新的RegexIterator(
新的文件系统发射器('/path/to/your/files'),
“(.+\ud+\.jpg$)”
);
/**@var SplFileObject$file*/
foreach($fsi作为$file){
如果($file->isFile()&&&$file->getMTime()
功能方法:
$days = 1;
array_map(
function($file) use ($days) {
if (!is_dir($file) && filemtime($file) < strtotime("-$days day")) {
unlink($file);
}
},
glob('/path/to/your/files/*_[1-9].jpg')
);
$days=1;
数组映射(
函数($file)使用($days){
如果(!is_dir($file)和&filemtime($file)
古老的命令:
$days = 1;
foreach (glob('/path/to/your/files/*_[1-9].jpg') as $file) {
if (!is_dir($file) && filemtime($file) < strtotime("-$days day")) {
unlink($file);
}
};
$days=1;
foreach(glob('/path/to/your/files/*.[1-9].jpg')作为$file){
如果(!is_dir($file)和&filemtime($file)
将if(filemtime($path.$file)
更改为if(filemtime($path.$file)
if(time()-($days*24*60*60))&预匹配('@\d+\.[a-zA-Z]{3}$@,$file))