文件锁定在PHP [英] file locking in php

查看:90
本文介绍了文件锁定在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个新来的人(隔壁的少年)写一些php代码来跟踪我的网站上的一些用法.我不熟悉php,所以我想问一下有关并发文件访问的问题.

I had a newcomer (the next door teenager) write some php code to track some usage on my web site. I'm not familiar with php so I'm asking a bit about concurrent file access.

我的本​​机应用程序(在Windows上)有时会通过点击包含我的php脚本的URL将一些数据记录到我的站点中.本机应用程序不检查返回的数据.

My native app (on Windows), occasionally logs some data to my site by hitting the URL that contains my php script. The native app does not examine the returned data.

        $fh = fopen($updateFile, 'a') or die("can't open file");
        fwrite($fh, $ip);
        fwrite($fh, ', ');
        fwrite($fh, $date);
        fwrite($fh, ', ');
        fwrite($fh, implode(', ', $_GET));
        fwrite($fh, "\r\n");
        fclose($fh);

这是一个人流量低的站点,数据并不重要.但是,如果两个用户发生冲突,并且脚本的两个实例各自尝试向该文件添加一行,该怎么办? php中是否有任何隐式文件锁定?

This is a low traffic site, and the data is not critical. But what happens if two users collide and two instances of the script each try to add a line to the file? Is there any implicit file locking in php?

上面的代码至少可以安全地锁定并永远不会将控制权交还给我的用户吗?文件会损坏吗?如果我上面的脚本每个月都删除文件,那么如果该脚本的另一个实例正在写入文件,该怎么办?

Is the code above at least safe from locking up and never returning control to my user? Can the file get corrupted? If I have the script above delete the file every month, what happens if another instance of the script is in the middle of writing to the file?

推荐答案

您应该在文件上加锁:

<?php
$fp = fopen($updateFile, 'w+');
if(flock($fp, LOCK_EX)) {
fwrite($fp, 'a');
flock($fp, LOCK_UN);
} else {
echo 'can\'t lock';
}

fclose($fp);

这篇关于文件锁定在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆