dongyouzhi7218 2015-12-10 01:38
浏览 28
已采纳

安全的PHP JSON日志记录

I am using JSON as a data store and over time I foresee that several parties might be wanting to write to my JSON file like a chat log within a short space of time.

<?php
$foo = json_decode(file_get_contents("foo.json"), true);
if (! is_array($foo["bar"])) { $foo["bar"] = array(); }
array_push($foo["bar"], array("time" => time(), "who" => $_SERVER['REMOTE_ADDR'], msg => $_GET['m']));
file_put_contents("foo.json", json_encode($foo, JSON_PRETTY_PRINT));
?>

So the above code works, but I am worried what happens if the file is read before it's written out, or some case where they are writing out at the same time, leading to some data loss?

What's a better or safer design, preferably using flat file storage (i.e. not databases)?

As for a bonus I really don't want to return to my client who made the request this that were was some "lock". Ideally the request is made to wait until it's safe to return.

  • 写回答

2条回答 默认 最新

  • duanpa5237 2015-12-10 02:21
    关注

    You can use the flock() function for this. What it does is it locks the file for all processes except the current one.

    http://php.net/manual/en/function.flock.php

    Basic usage:

    <?php
    
    $fp = fopen('path/to/data.json', 'r+');
    
    if (flock($fp, LOCK_EX)) // locks the file
    {
        // write to the file
    
        flock($fp, LOCK_UN); // remove the lock
    }
    
    fclose($fp);
    

    flock() is blocking by default. That means a process is waiting until it gets permission to access the lock. Have a look at the docs on how to implement a nonblocking version.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大