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);
}

图片转代码服务由CSDN问答提供 功能建议

我有一个非常简单的PHP程序,不想工作。 它向我返回与主题相同的错误,原因不明。

  $ 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($ 写,$ 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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题