PHP文件锁定机制

<?php
//如果多用户访问一个文件,采用文件锁定机制
/*
flock()文件锁定
*/
header("Content-Type:text/html;charset=utf8");
$filename = "message.txt";

//如果用户提交了, 就写入文件, 按一定格式写入
if(isset($_POST['dosubmit'])) {
//字段的分隔使用||, 行的分隔使用[n]
$mess = "{$_POST['username']}||".time()."||{$_POST['title']}||{$_POST['content']}[n]";

writemessage($filename, $mess);

}

if(file_exists($filename)) {
readmessage($filename);
}

function writemessage($filename, $mess) {
$fp = fopen($filename, "a");
// LOCK_EX写入锁
// LOCK_NB防止阻塞
if(flock($fp, LOCK_EX+LOCK_NB)) {

fwrite($fp, $mess);
//LOCK_UN释放锁
flock($fp, LOCK_UN+LOCK_NB);

} else {
echo "写入锁定失败!";
}

fclose($fp);
}

function readmessage($filename) {
// $mess = file_get_contents($filename);

$mess = "";

$fp = fopen($filename, "r");

//读锁定LOCK_SH
flock($fp, LOCK_SH+LOCK_NB);
//检测是否到文件结尾
while(!feof($fp)) {
$mess.=fread($fp, 1024);
}

flock($fp, LOCK_UN+LOCK_NB); //释放

$mess = rtrim($mess, "[n]");

$arrmess = explode("[n]", $mess);

foreach($arrmess as $m) {
list($username, $dt ,$title, $content) = explode("||", $m);

echo "<b>{$username}</b>, ".date("Y-m-d H:i").": <i>{$title}</i>, <u>{$content}</u><br><hr><br>";
}

fclose($fp);

}
?>

<form action="message.php" method="post">
用户: <input type="text" name="username" value="" /><br>
标题:<input type="text" name="title" value="" /><br>
内容:<textarea name="content" cols="40" rows="4"></textarea><br>
<input type="submit" name="dosubmit" value="留言" /><br>
</form>

posted on 2016-03-31 20:51  奋斗的寒霜  阅读(374)  评论(0编辑  收藏  举报