doujiao3346 2018-09-08 01:45
浏览 63
已采纳

警告:flock()期望参数1是资源,给定字符串

I have this very simple program in PHP that does not want to work. It returns the same error as topic for unknown reasons to me.

$file = 'counter.txt';
$counter = file_get_contents($file);
if(flock($file, LOCK_EX)){
    $counter += 1;
    echo $counter;
    $write = fopen($file, 'w') or die('Unable');
    fwrite($write, $counter);
    flock($file,LOCK_UN);
}
  • 写回答

1条回答 默认 最新

  • douzhiji2020 2018-09-08 01:49
    关注

    You have a few things out of order,

    $file = 'counter.txt';
    $counter = file_get_contents($file);
    $write = fopen($file, 'w') or die('Unable'); //move this line
    
    if(flock($write, LOCK_EX)){  //-- change this
       $counter += 1;
        echo $counter;
        fwrite($write, $counter);
        flock($write,LOCK_UN); //-- change this
    }
    

    The main problem is flock takes a (stream)resource as it's input, and the filename is just a string. So instead of $file you just need to use $write which is your file handle (resource), and then move fopen before the flock call.

    If you are writing a single line do this instead

    $file = 'counter.txt';
    $counter += 1;
    if(!file_put_contents($file, $counter, LOCK_EX)) or die('Unable');
    

    http://php.net/manual/en/function.file-put-contents.php

    It's pretty much equivalent to what you have there. Well except it's way shorter 3 vs 9 lines, easier, and Kooler.

    I could even reduce this further down to 1 line:

      if(!file_put_contents('counter.txt', ++$counter, LOCK_EX)) or die('Unable');
    

    The LOCK_EX flag is Lock exclusive, basically the same thing as flock, just in this case PHP handles all the file stream stuff for you.

    The real difference is if you do this in a loop, it's expensive getting file handles so to loop output into file_put_content is way less efficient then to open the file (outside the loop) and write to the same handle during inside a loop.

    Hesse the reason I said this above.

    If you are writing a single line do this instead

    Hope that makes sense.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化