By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,466 Members | 1,148 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,466 IT Pros & Developers. It's quick & easy.

Does Synchronization work properly in file handling in php?

P: 2
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.
Jul 26 '07 #1
Share this Question
Share on Google+
4 Replies


pbmods
Expert 5K+
P: 5,821
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.
Jul 26 '07 #2

ak1dnar
Expert 100+
P: 1,584
Moving thread from Php Articles section to the Forum.
-ajaxrand
Jul 27 '07 #3

pbmods
Expert 5K+
P: 5,821
Heya, Tushar.

Check out flock().
Jul 27 '07 #4

kovik
Expert 100+
P: 1,044
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.
Jul 27 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.