php 脚本删除超过 24 小时的文件,删除所有文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3126191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php script to delete files older than 24 hrs, deletes all files
提问by ChuckO
I wrote this php script to delete old files older than 24 hrs, but it deleted all the files including newer ones:
我编写了这个 php 脚本来删除超过 24 小时的旧文件,但它删除了所有文件,包括较新的文件:
<?php
$path = 'ftmp/';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ((time()-filectime($path.$file)) < 86400) {
if (preg_match('/\.pdf$/i', $file)) {
unlink($path.$file);
}
}
}
}
?>
回答by Mike
<?php
/** define the directory **/
$dir = "images/temp/";
/*** cycle through all files in the directory ***/
foreach (glob($dir."*") as $file) {
/*** if file is 24 hours (86400 seconds) old then delete it ***/
if(time() - filectime($file) > 86400){
unlink($file);
}
}
?>
You can also specify file type by adding an extension after the * (wildcard) eg
您还可以通过在 *(通配符)后添加扩展名来指定文件类型,例如
For jpg images use: glob($dir."*.jpg")
对于 jpg 图像使用: glob($dir."*.jpg")
For txt files use: glob($dir."*.txt")
对于 txt 文件,请使用: glob($dir."*.txt")
For htm files use: glob($dir."*.htm")
对于 htm 文件使用: glob($dir."*.htm")
回答by ssube
(time()-filectime($path.$file)) < 86400
If the current time and file's changed time are within86400 seconds of each other, then...
如果当前时间和文件的更改时间相差在86400 秒以内,则...
if (preg_match('/\.pdf$/i', $file)) {
unlink($path.$file);
}
I think that may be your problem. Change it to > or >= and it should work correctly.
我想那可能是你的问题。将其更改为 > 或 >=,它应该可以正常工作。
回答by Ignacio Vazquez-Abrams
- You want
>instead. - Unless you're running on Windows, you want
filemtime()instead.
- 你想要
>。 - 除非你在 Windows 上运行,否则你想要
filemtime()。
回答by cfv1000
<?php
$dir = getcwd()."/temp/";//dir absolute path
$interval = strtotime('-24 hours');//files older than 24hours
foreach (glob($dir."*") as $file)
//delete if older
if (filemtime($file) <= $interval ) unlink($file);?>
回答by saefry
working fine
工作正常
$path = dirname(__FILE__);
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
$timer = 300;
$filetime = filectime($file)+$timer;
$time = time();
$count = $time-$filetime;
if($count >= 0) {
if (preg_match('/\.png$/i', $file)) {
unlink($path.'/'.$file);
}
}
}
}
回答by Adam Pery
$path = '/cache/';
// 86400 = 1day
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ( (integer)(time()-filemtime($path.$file)) > 86400 && $file !== '.' && $file !== '..') {
unlink($path.$file);
echo "\r\n the file deleted successfully: " . $path.$file;
}
}
}

