PHP同步文件访问

PHP同步文件访问,php,file-access,Php,File Access,好的,好的。。所以现在我吓坏了 index1.php <? function write_file($filepath,$filecontent) { $openedfile = fopen($filepath,"w+"); //replace with $openedfile = fopen($filepath,"a"); just in case flock($openedfile, LOCK_EX); //add here fclose($openedfile); t

好的,好的。。所以现在我吓坏了

index1.php

<?
function write_file($filepath,$filecontent) {
    $openedfile = fopen($filepath,"w+"); //replace with $openedfile = fopen($filepath,"a"); just in case
    flock($openedfile, LOCK_EX);
//add here fclose($openedfile); to work
//add here $openedfile = fopen($filepath,"w+"); to work
    fwrite($openedfile,$filecontent);
    flock($openedfile, LOCK_UN);
    fclose($openedfile);
}
function read_file($filepath) {
    $openedfile = fopen($filepath,"r+");
    flock($openedfile, LOCK_SH);
    sleep(10);
    $filecontent = file_get_contents($filepath);
    flock($openedfile, LOCK_UN);
    fclose($openedfile);
    return $filecontent;
}
write_file("Readme.txt","test 1");
$f1 = read_file("Readme.txt");
echo $f1;
?>


在第二个php中,当index2.php执行时,它不再擦除readme.txt。

这与打开文件进行写入时,您的readme.txt实际上在很短的一段时间内是空的这一事实无关吗?我认为PHP删除了整个文本,然后用整个文本+附加内容替换它。当index1.php想要读取该文件时,index2.php可能刚刚清除了它?顺便说一下,您可以在apache日志中检查这一点


编辑:另外,在解锁文件后,index2.php立即控制它,用测试2覆盖测试1

看起来您在写入文件之前释放了锁。另见,你是对的。我再次检查,运行index2.php后readme.txt为空。我被误导了,因为之前我在执行index2.php后通过FTP(服务器不是本地的)检查readme.txt时,readme.txt包含“test1”。FTP是否有缓存或其他东西?FTP?在你的问题中没有任何字眼,你提到这与FTP有关。是的,FTP做的事情与本地文件系统不同,因为它只是一个协议和一个与之对话的服务器。然后,它取决于FTP服务器及其配置,具体发生了什么。查看FTP服务器的配置和文档,了解您如何影响其行为,以利于您的利益。实际上我不知道这一点。但是,将readme.txt的内容放入数据库可能更容易/更节省?这样可以更快地编辑和更改。@hakre它与FTP无关。他只是检查了readme.txt的内容,以验证它是否被更改了。@djeroneth:OP在一篇关于FTP的评论中问道,这就是为什么我想知道的原因。
<?
function write_file($filepath,$filecontent) {
    $openedfile = fopen($filepath,"w+"); //replace with $openedfile = fopen($filepath,"a"); to work
    flock($openedfile, LOCK_EX);
//add here fclose($openedfile); to work
//add here $openedfile = fopen($filepath,"w+"); to work
    fwrite($openedfile,$filecontent);
    flock($openedfile, LOCK_UN);
    fclose($openedfile);
}
function read_file($filepath) {
    $openedfile = fopen($filepath,"r+");
    flock($openedfile, LOCK_SH);
    $filecontent = file_get_contents($filepath);
    flock($openedfile, LOCK_UN);
    fclose($openedfile);
    return $filecontent;
}
write_file("Readme.txt","test 2");
$f1 = read_file("Readme.txt");
echo $f1;
?>
$openedfile = fopen($filepath,"w+");
$openedfile = fopen($filepath,"a");