Re: PHP Problem When Opening Same File?

  • From: "tribble" <lauraeaves@xxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Fri, 4 Jan 2008 15:03:41 -0500

Hi --
Try the flock command in php -- look up flock() in the php docs. That is what I 
use in my counter.
flock will lock a file temporarily to prevent simultaneous access. however, it 
seems I read somewhere that flock is not honored on some servers -- whether 
that has been fixed yet I don't know. So if you do use flock, your code may not 
be portable.

Another safer method is to use a database manager like mysql, which will 
coordinate access for you without any extra overhead.

Below is the modified code for a counter using flock that I got from "Jeff the 
Ultra guy":

counter.txt (the data file):
//Copyright 2003 by Anoetic Concepts -
//Change the file name in the next line to match your counter file. 
$cfile = "cgi-bin/counter.txt"; //Default: counter.dat
//Do you want the count displayed or just incremented? 
$displaycount = 1; //1=display, 0=increment only

$localip = ""; 
if ( ($fp = fopen ($cfile,"r+")) && flock($fp,LOCK_EX) ) {
    $ip = fgets ($fp,17); // fgets reads len - 1 and newline must be read 
    $ip = chop ($ip); 
    $count = fgets ($fp,10); 
    if ($REMOTE_ADDR == $localip) 
        $np = $ip; 
        $np = $REMOTE_ADDR; 
if ($np != $ip) 
    $count += 1; 
$np = sprintf ("%-15s\n", $np);
rewind ($fp); 
fputs ($fp,$np,16); 
fputs ($fp,$count,10); 
fclose ($fp); 
if ($displaycount) 
echo $count; 

  ----- Original Message ----- 
  From: Bryan Garaventa 
  To: programmingblind@xxxxxxxxxxxxx 
  Sent: Wednesday, January 02, 2008 11:20 PM
  Subject: PHP Problem When Opening Same File?

  Is it possible to query a file on the server to see if it's already opened by 
another script?

  My problem is this...

  I have a variable that is dynamically updated by a script, which increments a 
counter each time the page loads. 

  However, if two people simultaniously trigger the script to run at virtually 
the same moment, which has just recently happened, the first instance of the 
script takes the variable, opens the file and then writes the new value into 
the file, then closes it. At the same time, the second instance of the script 
is trying to access the same file, and finding no file (since it's already 
opened by the other instance), the counter defaults to zero, and that is then 
written in the new file instead of the incremented value.

  All of which totally screws up the counter.

  So, is there a way that I can check if the file is already open before having 
the script try to open the file and write new data to it?



Other related posts: