This code works - but in the case where there is an existing text file, it looks clunky. I think it should be possible not to have to close the text fle , then open it again in order to clear the content and write in the new value. But despite studying the php manual for fopen I can't figure another way that works. Is there a slicker way?
<?php
// increase the number in a text file by one
//the text file consists of one number only
$file = "count.txt";
// check if file exists
if ( !file_exists($file))
{
// if it does not, set counter to 0
$count = 1;
// create file
$handle = fopen($file, 'w') or die("can't open file");
//write the count as 0
fwrite ($handle, $count);
}
else
//if counter file exists open it
{
$handle = fopen ($file, 'r');
//read the number in the file
$count = fread($handle, 5);
//add one to it
$count++;
fclose($handle);
//clear the content previously in file and write value of $count
$handle = fopen ($file, 'w');
fwrite ($handle, $count);
}
fclose ($handle);
?>