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.

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

报告相同问题?

悬赏问题

  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程