PHP 锁定文本文件进行编辑?

标签 php file-locking

我有一个将输入写入文本文件的表单。 是否可以锁定一个文本文件进行编辑,并给出一个友好的消息“该文件已被其他用户编辑,请稍后再试”。

如果文件同时有多个编辑器,我想避免冲突。

这是当前添加条目的方式。

$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/

相关文章:

javascript - 如何获取使用 $.ajax 返回的 MySQL 查询结果

php - 返回不同模型的对象列表的 JOIN 查询?

php - 从单个表单向数据库添加多条记录?

c - Linux 中的文件锁定

c++ - 使用 boost::interprocess::file_lock 创建一个锁定文件

c - 文件锁允许打开文件

php - 使用 PDO 和 oops 选择查询

php - MySql 用于搜索具有不同值的相同 ID 的日期范围的可用汽车

python : Locking text file on NFS

c++ - 如何使用 C++ 在 Windows 中锁定文件?