はじめに
PHPのファイルシステム関数について整理する
ファイル書き込みの基本手順
・ファイルを開く
・ファイルをロックする
・ファイルに対して書き込みを行う
・ファイルを閉じる
file_write.php
$data[] = date('Y/m/d H:i:s');
$data[] = $_SERVER['SCRIPT_NAME'];
$data[] = $_SERVER['HTTP_USER_AGENT'];
$data[] = $_SERVER['HTTP_REFERER'];
$file = fopen('access.log', 'a') or die('ファイルを開けませんでした');
flock($file, LOCK_EX);
fwrite($file, implode("\t", $data) . "\n");
flock($file, LOCK_UN);
fclose($file);
print 'アクセスログを記録しました。';
fopen / fclose
ファイルを開く/ 閉じる
fopen(string $filename, string $mode[, bool $use_include_path = false]) : resource
$filename: ファイルのパス
$mode: オープンモード
$use_include_pat: include_pathパラメーターを利用するか
fwrite(fputs)
ファイルへの書き込み
fwrite(resource $hundle, string $string [, bool $length]) : int
$hundle: 書き込み対象のファイルハンドル
$string: 書き込む文字列
$length: 書き込む文字列の長さ
flock
ファイルへの同時書き込みを阻止するためにファイルをロックする
flock(resource $stream, int $operation) : int
$stream: ファイルハンドル
$operation: ロックモード