我有一个将输入写入文本文件的表单。 是否可以锁定一个文本文件进行编辑,并给出一个友好的消息“该文件已被其他用户编辑,请稍后再试”。
如果文件同时有多个编辑器,我想避免冲突。
这是当前添加条目的方式。
$content = file_get_contents("./file.csv"); $fh = fopen("./file.csv", "w"); fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm); fwrite($fh, "\n" . $content); fclose($fh);
有什么想法吗?
最佳答案
您可以使用flock()
函数来锁定文件。有关更多信息,请参阅 this
类似于:
<?php
$content = file_get_contents("./file.csv");
$fp = fopen("./file.csv", "w"); // open it for WRITING ("w")
if (flock($fp, LOCK_EX))
{
// do your file writes here
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);
flock($fh, LOCK_UN); // unlock the file
}
?>
关于PHP 锁定文本文件进行编辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15435619/