Forum Moderators: coopster

Message Too Old, No Replies

Global/Persistent Variable?

         

Emperor

1:19 am on Apr 8, 2005 (gmt 0)

10+ Year Member



Hi guys,

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.

ironik

1:49 am on Apr 8, 2005 (gmt 0)

10+ Year Member



No, php won't store variables persistantly between pages and visitors like that... it needs somewhere to store the information other that memory because memory is only assigned for the time it is processing the page.

If you want to count clicks reliably you'll have to go for a database or flat file, unless someone knows of another method?

Emperor

2:35 am on Apr 8, 2005 (gmt 0)

10+ Year Member



Hi,

Yes, that's what I figured. It seems pretty crazy to have to make a connection, open a database, etc. just to go: hits=hits+1

If I store it in a flat file I have to worry about parsing the whole thing, unless I keep a file for every link.

It kinda sucks.

ironik

2:48 am on Apr 8, 2005 (gmt 0)

10+ Year Member



If you only have a limited amount of pages you could store the links in one file as an array:

$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.