こんにちは!今回はPHPのfilemtime
関数について、基本から実践的な使い方まで詳しく解説します。
1. 基本的な使い方
// ファイルの最終更新時刻を取得
$filename = 'example.txt';
$modifiedTime = filemtime($filename);
// 読みやすい形式に変換
echo date('Y-m-d H:i:s', $modifiedTime);
2. 実践的な使用例
2-1. キャッシュの有効期限チェック
class CacheManager {
private $cacheDir;
private $maxAge; // 秒単位
public function __construct($cacheDir, $maxAge = 3600) {
$this->cacheDir = $cacheDir;
$this->maxAge = $maxAge;
}
public function isCacheValid($filename) {
$cachePath = $this->cacheDir . '/' . $filename;
if (!file_exists($cachePath)) {
return false;
}
$modifiedTime = filemtime($cachePath);
return (time() - $modifiedTime) < $this->maxAge;
}
public function cleanExpiredCache() {
$files = glob($this->cacheDir . '/*');
$now = time();
foreach ($files as $file) {
if ($now - filemtime($file) > $this->maxAge) {
unlink($file);
}
}
}
}
2-2. ファイルの変更監視
function checkFileChanges($files) {
static $lastCheck = [];
$changes = [];
foreach ($files as $file) {
$currentMtime = filemtime($file);
if (isset($lastCheck[$file]) && $lastCheck[$file] !== $currentMtime) {
$changes[] = [
'file' => $file,
'last_check' => date('Y-m-d H:i:s', $lastCheck[$file]),
'current' => date('Y-m-d H:i:s', $currentMtime)
];
}
$lastCheck[$file] = $currentMtime;
}
return $changes;
}
2-3. ファイル整理ツール
class FileOrganizer {
public function sortByModificationDate($directory) {
$files = [];
$entries = scandir($directory);
foreach ($entries as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
$path = $directory . '/' . $entry;
$mtime = filemtime($path);
$files[] = [
'name' => $entry,
'path' => $path,
'modified' => $mtime,
'modified_formatted' => date('Y-m-d H:i:s', $mtime)
];
}
// 更新日時でソート
usort($files, function($a, $b) {
return $b['modified'] - $a['modified'];
});
return $files;
}
}
3. エラーハンドリング
function safeGetModifiedTime($filename) {
try {
if (!file_exists($filename)) {
throw new Exception("ファイルが存在しません");
}
if (!is_readable($filename)) {
throw new Exception("ファイルを読み取れません");
}
clearstatcache(true, $filename);
$mtime = filemtime($filename);
if ($mtime === false) {
throw new Exception("更新時刻の取得に失敗しました");
}
return [
'timestamp' => $mtime,
'formatted' => date('Y-m-d H:i:s', $mtime)
];
} catch (Exception $e) {
error_log("Error in safeGetModifiedTime: " . $e->getMessage());
return false;
}
}
4. タイムゾーンを考慮した実装
function getModifiedTimeWithTimezone($filename, $timezone = 'Asia/Tokyo') {
$originalTz = date_default_timezone_get();
try {
date_default_timezone_set($timezone);
$mtime = filemtime($filename);
$result = [
'timestamp' => $mtime,
'formatted' => date('Y-m-d H:i:s', $mtime),
'timezone' => $timezone
];
date_default_timezone_set($originalTz);
return $result;
} catch (Exception $e) {
date_default_timezone_set($originalTz);
throw $e;
}
}
5. バックアップ機能の実装
function createBackup($filename) {
if (!file_exists($filename)) {
throw new Exception("元ファイルが存在しません");
}
$mtime = filemtime($filename);
$backupName = sprintf(
'%s_%s.bak',
pathinfo($filename, PATHINFO_FILENAME),
date('Ymd_His', $mtime)
);
if (copy($filename, $backupName)) {
return [
'original' => $filename,
'backup' => $backupName,
'mtime' => date('Y-m-d H:i:s', $mtime)
];
}
throw new Exception("バックアップの作成に失敗しました");
}
まとめ
filemtime関数を使用する際は、以下の点に注意しましょう:
- キャッシュの影響を考慮する(clearstatcache()の使用)
- 適切なエラーハンドリングを実装する
- タイムゾーンの設定を確認する
- パーミッションの確認を行う
- ファイルの存在確認を忘れない
主な用途:
- キャッシュ管理
- ファイルの変更監視
- バックアップ管理
- ファイルの整理・分類
- 更新日時ベースの処理
これらの点を意識することで、より信頼性の高いファイル管理システムを構築できます。