CakePHP2.6系
ディレクトリにあるファイルを走査して、最終更新日時が現時刻の1時間前以前なら削除する処理を書きました。
HogeController.php
public function cleanup() {
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
$uploadPath = WWW_ROOT.'file'.DS.'dir_name';
$pdfDir = new Folder($uploadPath);
$files = $pdfDir->find('.*\.pdf'); // 正規表現でフィルタリングできます
foreach ($files as $fileName) {
$file = new File($uploadPath.DS.$fileName);
$lastUpdateTime = $file->lastChange();
if ($lastUpdateTime < time() - 3600) {
// 最終更新日時が1時間前以前なら削除
$file->delete();
}
}
$files = $pdfDir->find('.*\.pdf');
}
参考: Folder & File ? CakePHP Cookbook 2.x ドキュメント
これをcronで回すなら、こんな感じ。
まずはcronから実行するshellを用意します。
app/Console/Command/HogeShell.php
App::uses('HogeController', 'Controller');
class HogeShell extends AppShell
{
public function startup()
{
parent::startup();
$this->HogeController = new HogeController();
}
public function cleanup()
{
$this->out($this->HogeController->cleanup());
}
コマンドラインで実行できるかチェック。
php ./app/Console/cake.php hoge creanup
動いたらcrontabに追加。
00 * * * * php /var/www/html/project/app/Console/cake.php hoge cleanup
