Valhalla Legends Archive

Programming => Web Development => Topic started by: j0k3r on January 18, 2004, 06:46 AM

Title: Crude PHP Counter
Post by: j0k3r on January 18, 2004, 06:46 AM
I'm trying to build a PHP counter (not very good, but it'll do the job) and can't figure out what's going wrong. Basically it reads the number (what the counter is at) from a text file and increments it, puts it to the screen, writes the updated number back to the text file and closes it.


<?php
/*source of file*/
$filename = 'current.txt';
/*open the file (r+ for read+write)*/
$fp = fopen($filename,'r+');
/*read the file and store it in $currentval (1 line)*/
$currentval = fread($fp, filesize($filename));
/*increment the value (because it's a counter)*/
$currentval++;
/*write it to the screen*/
echo $currentval;
/*write the incremented value to the source file*/
fwrite ($fp, $currentval);
/*close the file*/
fclose ($fp);
?>


No errors are generated from the code, and it just seems as though fwrite() isn't working (I'm probably not using it properly). Online Function Reference at: http://ca.php.net/function.file
Title: Re:Crude PHP Counter
Post by: j0k3r on January 18, 2004, 01:23 PM
I tried uploading, and it worked sort of, ended up fixing it eventually... For those interested:
<?php
$filename
= 'current.txt';   /*source of file*/  
$fp = fopen($filename,'r+');   /*open the file (r+ for read+write)*/  
flock($fp, 2);         /*lock the file*/  
$currentval = fread($fp, filesize($filename));   /*read the file and store it in $currentval (1 line)*/
$currentval++;               /*increment the value (because it's a counter)*/  
echo $currentval;      /*write it to the screen*/
fseek($fp,0);         /*go to beginning of file*/  
fputs ($fp, $currentval);   /*write the incremented value to the source file*/  
flock($fp, 3);         /*unlock the file*/  
fclose ($fp);         /*close the file*/  
?>