首页 > 解决方案 > PHP如何停止写入和截断

问题描述

我正在尝试在 php 中实现一种原子获取和设置。这是我到目前为止得到的。

function atomic_get_and_set($filename, $oldData, $newData)
{
  $size = filesize($filename) + 100000;
  $fp = fopen($filename, "c+");
  $failure = "0";
  if (flock($fp, LOCK_EX)) {
    $current_content = fread($fp, $size);
    if($current_content == $oldData) {
      rewind($fp);
      fwrite($fp, $newData);
    } else {
      $failure = "1".$current_content;
    }
    flock($fp, LOCK_UN);
  }
  fclose($fp);
  return $failure;
}

如果我们读取的不是预期的旧日期“0”,则我试图返回以“1”开头的文件内容,否则写入文件。

我必须使用 C+ 或 a+ 打开文件,以确保在打开文件时不会删除文件内容。但是,以下情况失败:

 file_put_contents("test.txt", "hello world");
 atomic_get_and_set("test.txt", "hello world", "hallo");

确实,文件的结果是“你好世界”而不仅仅是“你好”,因为我没有找到如何告诉他在fwrite. 有谁知道该怎么做?

标签: phpconcurrencyfopenatomicfwrite

解决方案


推荐阅读