所有请求中的PHP Persist变量

编程入门 行业动态 更新时间:2024-10-28 00:14:46
本文介绍了所有请求中的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变量

本文发布于:2023-11-26 14:22:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634120.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   PHP   Persist

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!