所有请求中的PHP Persist变量 [英] PHP Persist variable across all requests

查看:83
本文介绍了所有请求中的PHP Persist变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

下面是一个示例,以帮助说明: 我想要一个这样的脚本,它可以计数.无论哪个用户/浏览器打开该URL.

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;

我希望将值存储在内存中.当apache重新启动时,不需要持久化数据,并且数据对于线程安全也没有那么重要.

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.

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

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.

推荐答案

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

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

这篇关于所有请求中的PHP Persist变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆