phplamp

PHP Persist variable across all requests


In some languages C# or .NET this would be a static variable, but in PHP the memory is cleared after each request. I want the value to persist across all requests. I don't wan't $_SESSION because that is different for each user.

To help explain here is an example: I want to have a script like this that will count up. No matter which user/browser opens the url.

<?php
function getServerVar($name){
    ...
}
function setServerVar($name,$val){
    ...
}
$count = getServerVar("count");
$count++;
setServerVar("count", $count);
echo $count;

I want the value stored in memory. It will not be something that needs to persist when apache restarts and the data is not that important that it needs to be thread safe.

UPDATE: I'm fine if it holds different values per server in a loadbalanced environment. Static variables in C# or Java will not be in sync either.


Solution

  • You would typically use a database to store the count.

    However as an alternative you could do so using a file:

    <?php
    $file = 'count.txt';
    if (!file_exists($file)) {
        touch($file);
    }
    
    //Open the File Stream
    $handle = fopen($file, "r+");
    
    //Lock File, error if unable to lock
    if(flock($handle, LOCK_EX)) {
        $size = filesize($file);
        $count = $size === 0 ? 0 : fread($handle, $size); //Get Current Hit Count
        $count = $count + 1; //Increment Hit Count by 1
        echo $count;
        ftruncate($handle, 0); //Truncate the file to 0
        rewind($handle); //Set write pointer to beginning of file
        fwrite($handle, $count); //Write the new Hit Count
        flock($handle, LOCK_UN); //Unlock File
    } else {
        echo "Could not Lock File!";
    }
    
    //Close Stream
    fclose($handle);