有没有办法使用PHP来确定文件夹中图像的文件年龄?
我想删除2小时之前的旧文件,如果在上传到文件夹时不添加时间戳名称,是否可能实现?
如果可以,请给我一个例子!
谢谢
有没有办法使用PHP来确定文件夹中图像的文件年龄?
我想删除2小时之前的旧文件,如果在上传到文件夹时不添加时间戳名称,是否可能实现?
如果可以,请给我一个例子!
谢谢
if (time()-filemtime($filename) > 2 * 3600) {
// file older than 2 hours
} else {
// file younger than 2 hours
}
<?php
// outputs e.g. somefile.txt was last modified: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>
<?php
function humanTiming ($time)
{
// to get the time since that moment
$time = time() - $time;
// time unit constants
$timeUnits = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
// iterate over time contants to build a human
$humanTiming;
foreach ($timeUnits as $unit => $text)
{
if ($time < $unit)
continue;
$numberOfUnits = floor($time / $unit);
// human readable token for current time unit
$humanTiming = $humanTiming.' '.$numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
// compute remaining time for next loop iteration
$time -= $unit*$numberOfUnits;
}
return $humanTiming;
}
$filename = '/path/to/your/file.extension';
if (file_exists($filename))
{
echo 'Now = '.date ("Y-m-d H:i:s.", time());
echo "<br/>$filename was last modified on " . date ("Y-m-d H:i:s.", filemtime($filename));
$time = strtotime('2010-04-28 17:25:43');
$time = filemtime($filename);
echo '<br/>File age is '.humanTiming($time).'.';
$fileAge = time()-filemtime($filename);
echo '<br/>Is file older than 2 hours? '.(($fileAge < (2*3600))?'No':'Yes').'.';
}
?>
Now = 2013-01-29 09:10:12.
/path/to/your/file.extension was last modified on 2013-01-29 08:07:52.
File age is 1 hour 2 minutes 20 seconds.
Is file older than 2 hours? No.
请注意,在NAS/SAN存储设备中,最新文件的文件时间可能与PHP time()不同,因为这些存储设备可能有自己的时钟。我认为这样的配置很少见,但它给我带来了一些麻烦。
尝试使用{{link1:filemtime()
}}
int filemtime ( string $filename )
filename
: 文件路径。// outputs e.g. somefile.txt was last modified: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
您可以使用上次文件修改的日期/时间:
clearstatcache()
函数。我在一个共享 cPanel 主机上实现了一个测试,每秒钟循环一次,并发现 filemtime()
函数在第一次迭代后返回了一个缓存时间,除非在调用它之前调用了 clearstatcache()
函数。 - Volomike