Forum Moderators: coopster
Can I make a global persistent variable? Here is a perfect example: I want to make a click counter, so I can count the number of times someone clicks a link. It would be nice if I didn't have to access a datababe or use a flat file to save and update the value; even if I'm counting 100 links it's only 100 integers in memory which is negligible.
Thanks.
If you want to count clicks reliably you'll have to go for a database or flat file, unless someone knows of another method?
$file = 'myfile.txt';
$fp = fopen($file, 'r+');
// read from content into array
$linkArray = array();
$linkArray = @unserialize(fread($fp, filesize($file)));
// Increment current link's hit counter
if (isset($linkArray['page_name'])
{
$linkArray['page_name'] ++;
} else {
$linkArray['page_name'] = 1;
}
@fwrite($fp, serialize($linkArray));
fclose($fp);
It's in-elegant, and I would not do this in the long term, but it saves you having to worry about writing something that will parse the file.
It's also untested, so apologies if it doesn't work right of the bat.