こんにちは!今回はPHPのfileatime
関数について詳しく解説します。この関数は、ファイルの最終アクセス時刻を取得するために使用されます。
基本的な使い方
// ファイルの最終アクセス時刻を取得
$filename = 'example.txt';
$accessTime = fileatime($filename);
// UNIXタイムスタンプを読みやすい形式に変換
echo date('Y-m-d H:i:s', $accessTime);
実践的な使用例
1. ファイル情報の表示
function getFileInfo($filename) {
if (!file_exists($filename)) {
throw new Exception("ファイル '{$filename}' が存在しません。");
}
return [
'last_access' => fileatime($filename),
'last_modified' => filemtime($filename),
'created_time' => filectime($filename),
'size' => filesize($filename),
];
}
// 使用例
try {
$info = getFileInfo('document.txt');
echo "最終アクセス日時: " . date('Y-m-d H:i:s', $info['last_access']) . "\n";
echo "最終更新日時: " . date('Y-m-d H:i:s', $info['last_modified']) . "\n";
echo "作成日時: " . date('Y-m-d H:i:s', $info['created_time']) . "\n";
echo "ファイルサイズ: " . $info['size'] . " bytes\n";
} catch (Exception $e) {
echo "エラー: " . $e->getMessage();
}
2. 古いファイルの検出
function findOldFiles($directory, $daysOld = 30) {
$oldFiles = [];
$currentTime = time();
$threshold = $currentTime - ($daysOld * 24 * 60 * 60);
$files = scandir($directory);
foreach ($files as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$fullPath = $directory . '/' . $file;
$accessTime = fileatime($fullPath);
if ($accessTime < $threshold) {
$oldFiles[] = [
'file' => $file,
'last_access' => date('Y-m-d H:i:s', $accessTime),
'days_since_access' => floor(($currentTime - $accessTime) / (24 * 60 * 60))
];
}
}
return $oldFiles;
}
3. キャッシュ管理
class CacheManager {
private $cacheDir;
private $maxAge; // 秒単位
public function __construct($cacheDir, $maxAge = 3600) {
$this->cacheDir = $cacheDir;
$this->maxAge = $maxAge;
}
public function isCacheValid($filename) {
$fullPath = $this->cacheDir . '/' . $filename;
if (!file_exists($fullPath)) {
return false;
}
$lastAccess = fileatime($fullPath);
return (time() - $lastAccess) < $this->maxAge;
}
public function cleanOldCache() {
$files = glob($this->cacheDir . '/*');
$currentTime = time();
foreach ($files as $file) {
if ($currentTime - fileatime($file) > $this->maxAge) {
unlink($file);
}
}
}
}
注意点
1. キャッシュのクリア
// キャッシュをクリアしてから時刻を取得
clearstatcache(true, $filename);
$accessTime = fileatime($filename);
2. エラーハンドリング
function safeGetAccessTime($filename) {
try {
if (!file_exists($filename)) {
throw new Exception("ファイルが存在しません");
}
if (!is_readable($filename)) {
throw new Exception("ファイルを読み取れません");
}
$accessTime = fileatime($filename);
if ($accessTime === false) {
throw new Exception("アクセス時刻の取得に失敗しました");
}
return $accessTime;
} catch (Exception $e) {
error_log("Error: " . $e->getMessage());
return false;
}
}
3. タイムゾーンの考慮
function getFileTimesWithTimezone($filename, $timezone = 'Asia/Tokyo') {
date_default_timezone_set($timezone);
$accessTime = fileatime($filename);
return [
'unix_timestamp' => $accessTime,
'formatted_time' => date('Y-m-d H:i:s', $accessTime),
'timezone' => $timezone
];
}
まとめ
fileatime関数を使用する際は、以下の点に注意しましょう:
- キャッシュの影響を考慮する
- 適切なエラーハンドリングを実装する
- タイムゾーンの設定を確認する
- パーミッションの確認を行う
- パフォーマンスへの影響を考慮する
また、以下のような場合にfileatime関数が特に有用です:
- キャッシュファイルの管理
- 古いファイルの検出と削除
- ファイルアクセスの監視
- バックアップ戦略の実装
これらの点を意識することで、より効果的にファイルのアクセス時刻を活用できます。