Connecting Tech Pros Worldwide Forums | Help | Site Map

Does Synchronization work properly in file handling in php?

Newbie
 
Join Date: Jul 2007
Posts: 2
#1: Jul 26 '07
hello,
i have prepared a php file for visitcount. that creates a text file per

day. as soon as any user visits that page ,a counter is incremented. but on

my site there is lots of trafic. that's why counter again starts with zero

. and file also written to null.b'coz multiple users(abt 1 to 10 lakh) can

visit page at same time.

so i want to know if code is right then what is the problem?
how can we solve this proble? is there any locking file mechanism in php?
code :
Expand|Select|Wrap|Line Numbers
  1.  $count_path = "../count_visit/".date("d-m-Y").".txt";
  2.  
  3.        if(file_exists($count_path))
  4.        {
  5.         $handle = fopen($count_path, 'r');
  6.                     $read_count= fread($handle, filesize($count_path));     
  7.  
  8.  
  9.                     fclose($handle);
  10.               /* or used    $read_count = file_get_contents($count_path);
  11.               */         
  12.                    if($read_count <> '' )
  13.                    {
  14.                        $inc_count = (int)$read_count + 1;
  15.                        $handle = fopen($count_path, 'w');
  16.                        fwrite($handle, $inc_count);
  17.                        fclose($handle);  
  18.                     }
  19.                  }
  20.                  else
  21.        {
  22.                       // executes when any user visits first time
  23.                       $handle = fopen($count_path, 'w');
  24.                        fwrite($handle, '1' );
  25.                       fclose($handle);
  26.         }
Plz solve this problem.

pbmods's Avatar
Site Moderator
 
Join Date: Apr 2007
Location: Texas
Posts: 5,435
#2: Jul 26 '07

re: Does Synchronization work properly in file handling in php?


Heya, Tushar.

Please use CODE tags when posting source code. See the REPLY GUIDELINES on the right side of the page next time you post.
ak1dnar's Avatar
Moderator
 
Join Date: Jan 2007
Location: Colombo
Posts: 1,440
#3: Jul 27 '07

re: Does Synchronization work properly in file handling in php?


Moving thread from Php Articles section to the Forum.
-ajaxrand
pbmods's Avatar
Site Moderator
 
Join Date: Apr 2007
Location: Texas
Posts: 5,435
#4: Jul 27 '07

re: Does Synchronization work properly in file handling in php?


Heya, Tushar.

Check out flock().
volectricity's Avatar
Expert
 
Join Date: Jun 2007
Location: Baltimore
Posts: 587
#5: Jul 27 '07

re: Does Synchronization work properly in file handling in php?


File-locking may give you unexpected results when multiple visitors come, as some of them will be disenfranchised.

If you have access to a database, you could do this very easily there, as it accounts for multiple queries within itself.
Reply