PHP 在所有请求中保留变量

Eri*_*ric 10 php lamp

在某些语言 C# 或 .NET 中,这将是静态变量,但在 PHP 中,每次请求后都会清除内存。我希望该值在所有请求中持续存在。我不想 $_SESSION 因为每个用户的情况都不同。

为了帮助解释这里有一个例子: 我想要一个像这样的可以计数的脚本。无论哪个用户/浏览器打开该网址。

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

我想要将值存储在内存中。当apache重新启动时,它不会是需要持久化的东西,并且数据也没有那么重要,以至于需要线程安全。

更新:如果它在负载平衡环境中每个服务器保存不同的值,我很好。C# 或 Java 中的静态变量也不会同步。

Pet*_*tah 1

您通常会使用数据库来存储计数。

但是,作为替代方案,您可以使用文件来执行此操作:

<?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);
Run Code Online (Sandbox Code Playgroud)