警告: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);
}

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.