账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    PHP并发读写文件问题 高手请进!
    31
    0

    ajax1.html三个ajax方法同时访问ajax1.php,ajax1.php中有进行文件data.php读写,由于三个ajax方法访问频率特别高,就产生了并发访问,导致读写出错,使用了flock()还是会出错,请高手们指导一下怎么解决呢?

    ajax1.html代码:

    var a = 1;
    var b = 1;
    var c = 1;
    function ajax1(){
        $.get('ajax1.php?from=a&value='+a, function(res){
            $('#ajax1').text(a);
            a++;
            if(res == 1){
                ajax1();
            }
        });
    }
    function ajax2(){
        $.get('ajax1.php?from=b&value='+b, function(res){
            $('#ajax2').text(b);
            b++;
            if(res == 1){
                ajax2();
            }
        });
    }
    function ajax3(){
        $.get('ajax1.php?from=c&value='+c, function(res){
            $('#ajax3').text(c);
            c++;
            if(res == 1){
                ajax3();
            }
            
        });
    }
    
    function beginAjax(){
        ajax1();
        ajax2();
        ajax3();
    }

    ajax1.php代码:

    $from = $_GET['from'];
    $value = $_GET['value'];
    
    $data = is_array(include 'data.php')? include 'data.php': array();
    
    $data[] = $from .'-'. $value;
    
    $file = fopen('data.php', 'w');
    $lock = flock($file, LOCK_EX);
    if($lock){
        fwrite($file, '<?php');
        fwrite($file, PHP_EOL);
        fwrite($file, 'return ');
        fwrite($file, var_export($data, true));
        fwrite($file, ';');
        flock($file, LOCK_UN);
    }
    fclose($file);
    exit('1');

    data.php代码(以下数据是出错了的数据):

    return array (
      0 => 'b-3',
    );1 => 'a-1',
      2 => 'c-1',
      3 => 'b-2',
      4 => 'a-2',
      5 => 'c-2',
    );
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 这里是哪 普通会员 1楼

      在PHP中,如果你需要并发读写文件,你可以使用PHP的内置函数fopen()fclose()。以下是一个简单的例子:

      ```php

      ```

      在这个例子中,我们首先创建了一个名为file.txt的文件,并使用fopen()函数打开它。然后,我们使用fwrite()函数开始写入一些文本到文件中。然后,我们使用fclose()函数关闭文件。接着,我们再次使用fopen()函数打开文件,然后使用fgets()函数开始读取文件中的每一行。最后,我们使用fclose()函数关闭文件。

      注意,PHP的fopen()fclose()函数在读写文件时需要指定正确的模式,以便正确地读取或写入文件。在本例中,我们使用了'w'模式,这将使文件写入模式,而'r'模式将使文件读取模式。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部