PHP Persist variable across all requests

2019-03-02 00:56发布

问题:

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.

回答1:

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);


回答2:

In php your going to have to use an external store that all servers share. The most commonly used tool is memcached, but sql and redis both work fine for this use case.



回答3:

The only way to do taht is, like bspates said, a tool that does not depend on any resource on your server. If you have various servers, you cannot rely on memory-based mechanisms on each machine. You have to store this number outside the servers, because each server will store the value for its own file or memory.

File writting, like $_SESSION, will work if you have only one server to receive your requests. For more than one server, you need any type of database where all your servers will communicate with.



标签: php lamp