Page 1 of 1

cannot update counter file

Posted: Thu Jun 17, 2004 11:50 am
by psmshankar
I have my counter.php file in my root directory.
it has the following code.

Code: Select all

<?php
$COUNTER_FILE = "count_data.txt";  

if (file_exists($COUNTER_FILE)) 
{
	// Open, read, increment, save and close file.
	$fp = fopen("$COUNTER_FILE", "r+");
	flock($fp, 1);
	$count = fgets($fp, 4096);
	//echo "<br> count = $count";
	$count += 1; 
	//echo "<br> count = $count";
	fseek($fp,0);
	fputs($fp, $count);
	flock($fp, 3);
	fclose($fp);
} 
else 
{
	// Create a file with initial data as 1.
	$fp = fopen("$COUNTER_FILE", "w");
	flock($fp, 1);
	$count = fgets($fp, 4096);
	if(!$count) $count = 1;
	fseek($fp,0);
	fputs($fp, $count);
	flock($fp, 3);
	fclose($fp);
}

?>
But the count_data.txt files doesn't get incremented...
I'm running PHP 4.3.1, Apache 1.3 under win2k
If its in windows the first thing to debug is to check the file permission ..but i'm running only windows??
whats the problem?

Posted: Thu Jun 17, 2004 11:55 am
by feyd
try switching the the modes to "ab" and "wb" respectively...

Posted: Thu Jun 17, 2004 11:57 am
by markl999
Seems like a hard way of doing it too. I'd just do:

Code: Select all

<?php
define('COUNTER_FILE', 'count_data.txt');
if(file_exists(COUNTER_FILE)){
  $count = file_get_contents(COUNTER_FILE);
} else {
  $count = 0;
}
$count++;
$fp = fopen(COUNTER_FILE, 'w');
fputs($fp, $count);
fclose($fp);

Posted: Thu Jun 17, 2004 8:33 pm
by psmshankar
thanks markl999 & feyd.
read the following in php manual
Note: The mode may contain the letter 'b'. This is useful only on systems which differentiate between binary and text files (i.e. Windows. It's useless on Unix). If not needed, this will be ignored.
If i include 'b' means the file is binary, is it?
In my case it's a text file only? can you xplain this?

why not it worked with 'r+' and 'w' respectively in my code?

Posted: Thu Jun 17, 2004 8:37 pm
by feyd
it doesn't really matter.. windows, technically doesn't care if a file's binary or not.. I just find it easier to deal with all files as binaries.

Posted: Thu Jun 17, 2004 8:53 pm
by psmshankar
hey then y it didn't work for me that script?

Posted: Thu Jun 17, 2004 8:55 pm
by feyd
because windows wants either one in there.. for some reason.. I dunno. I didn't write the internal php function.. under C, it'd default to text, last I worked with fopen..

Posted: Thu Jun 17, 2004 9:15 pm
by psmshankar
:? :roll: