The PHP documentation says:
flock() operates on handle which must be an open file pointer. operation is one of the following values:
To acquire a shared lock (reader), set operation to LOCK_SH (set to 1 prior to PHP 4.0.1).
To acquire an exclusive lock (writer), set operation to LOCK_EX (set to 2 prior to PHP 4.0.1).
To release a lock (shared or exclusive), set operation to LOCK_UN (set to 3 prior to PHP 4.0.1).
If you don't want flock() to block while locking, add LOCK_NB (4 prior to PHP 4.0.1) to operation.
To me, that doesn't make all that much sense because of the jargon used 🙁
Q1: Can someone please explain to me the difference between LOCK_SH and LOCK_EX. Where should I use either one?
Q2: I have a basic hit counter:
$count_file='count_data.txt';
$count_handle=fopen($count_file,'r');
$count_hits=fread($count_handle,filesize($count_file));
fclose($count_handle);
$count_hits++;
$count_handle=fopen($count_file,'w');
flock($count_handle,LOCK_EX);
fwrite($count_handle,$count_hits);
flock($count_handle,LOCK_UN);
fclose($count_handle);
echo number_format($count_hits);
I have used locking when writing to the file - is this sufficient enough?
Thank you 🙂