TOP ▲
itcore TOP プログラムパーツ
uLogKeyTime 時間記録ログファイルを作成する。指定したキーをユニークにして新しい順に保存する。 | itcore 2018年
PHP
関数
<?php
// 時間記録ログファイルを作成する。指定したキーをユニークにして新しい順に保存する。
function uLogKeyTime($file, $key) {
$a_data = array();
// 現在のログファイルを読み込む
if (file_exists($file)) {
$data = file_get_contents($file);
$a_data = explode("\n", $data);
}
// ログファイルに書き込む
$fp = fopen($file, "w");
$data = "$key\t" . date("Y-m-d H:i:s") . "\n";
fwrite($fp, $data);
foreach($a_data as $data) {
if ("" == trim($data)) continue;
list($key1, $dt1) = explode("\t", "$data\t");
if ($key1 != $key) fwrite($fp, $data . "\n");
}
fclose($fp);
}
?>
テスト
<?php include "uLogKeyTime.func"; ?>
<?php
$file = "/tmp/uLogKeyTime.log";
shell_exec("/bin/rm $file");
uLogKeyTime($file, "key1");
sleep(1);
uLogKeyTime($file, "key2");
echo "[1]<br>\n" . nl2br(htmlspecialchars(shell_exec("cat $file")));
sleep(1);
uLogKeyTime($file, "key1");
echo "[2]<br>\n" . nl2br(htmlspecialchars(shell_exec("cat $file")));
?>
実行結果
[1]
key2 2025-05-01 14:52:09
key1 2025-05-01 14:52:08
[2]
key1 2025-05-01 14:52:10
key2 2025-05-01 14:52:09