PHP同时文件写入 [英] PHP Simultaneous File Writes

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

问题描述

我有两个不同的PHP文件,都写入同一个文件。每个PHP脚本都由两个不同的HTML页面的用户操作调用。我知道两个PHP文件都可以被调用,但是两个PHP文件会同时尝试写入文件吗?如果是,会发生什么?另外,有可能使PHP中的一个失败(文件写入将失败,另一个PHP可以写入文件),因为一个PHP函数不太重要。


<解决这个问题的常用方法是让这两个脚本都使用 flock() 用于锁定:

  $ f = fopen('some_file','a'); 
flock($ f,LOCK_EX);
fwrite($ f,some_line \\\
);
flock($ f,LOCK_UN);
fclose($ f);

这会导致脚本在写入之前等待对方完成该文件。如果你喜欢,那么不太重要的脚本就可以做到:
$ b $ $ $ $ $ $ $ $ $ f = fopen('some_file','a') ;
if(flock($ f,LOCK_EX | LOCK_NB)){
fwrite($ f,some_line \\\
);
flock($ f,LOCK_UN);
}
fclose($ f);

如果发现某个文件正在忙于执行任何操作, p>

I have two different PHP files that both write to the same file. Each PHP script is called by a user action of two different HTML pages. I know it will be possible for the two PHP files to be called, but will both PHP files attempt to write to the file at the same time? If yes, what will happen? Also, it is possible to make one of the PHP fail gracefully (file write will just fail, and the other PHP can write to the file) as one PHP function is less important that the other.

解决方案

The usual way of addressing this is to have both scripts use flock() for locking:

$f = fopen('some_file', 'a');
flock($f, LOCK_EX);
fwrite($f, "some_line\n");
flock($f, LOCK_UN);
fclose($f);

This will cause the scripts to wait for each other to get done with the file before writing to it. If you like, the "less important" script can do:

$f = fopen('some_file', 'a');
if(flock($f, LOCK_EX | LOCK_NB)) {
    fwrite($f, "some_line\n");
    flock($f, LOCK_UN);
}
fclose($f);

so that it will just not do anything if it finds that something is busy with the file.

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

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