Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Persist variable across all requests

Tags:

php

lamp

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.

like image 225
Eric Avatar asked Apr 09 '26 06:04

Eric


2 Answers

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);
like image 62
Petah Avatar answered Apr 11 '26 21:04

Petah


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.

like image 21
bspates Avatar answered Apr 11 '26 19:04

bspates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!