Andry R.
Andry R.

Reputation: 199

How can I store data in RAM memory using PHP?

Is there a way to store small data in RAM memory using PHP so that I can have access to the data between different session instead of regenerating it. Something similar to memcached (I don't have access to memcahced). My current solution is just to save the data in file.

Upvotes: 12

Views: 15810

Answers (4)

Strae
Strae

Reputation: 19445

APCu?

It works differents from memcached; in memcached you can access the data from various languages (c, python, etc..) while APCu works only for PHP.

Ensure that APC is installed correctly. Add extension=apcu.so in php.ini? Restart the server (apache, etc)

This is a simple test:

<?php
/*
 * page.php
 * Store the variable for 30 seconds,
 * see http://it.php.net/manual/en/function.apcu-add.php
 * */
if(apcu_add('foo', 'bar', 30)){
    header('Location: page2.php');
}else{
    die("Cant add foo to apcu!");
}

<?php
/*
 * page2.php
 * */
echo 'foo is been set as: ' . apcu_fetch('foo');

Consider using apcu_add over apcu_store; the only difference between them is that apcu_add doesn't overwrite the variable but will fail if called twice with the same key:

Store the variable using this name. keys are cache-unique, so attempting to use apcu_add() to store data with a key that already exists will not overwrite the existing data, and will instead return FALSE. (This is the only difference between apcu_add() and apcu_store().)

It's a matter of taste/task of the script, but the example above works with apcu_store too.

Upvotes: 14

kijin
kijin

Reputation: 8910

Create a file in /dev/shm and it will be kept in memory until the machine is rebooted. This may or may not be faster than using any old file, depending on your usage pattern.

Upvotes: 3

Paul Sonier
Paul Sonier

Reputation: 39480

You could always use an in-memory DB to save the data. Possibly overkill, though.

Upvotes: 8

Pekka
Pekka

Reputation: 449435

I am assuming you are on a shared server of some sort.

memcached or another caching solution is indeed the only way to do this.

Sessions, the most prominent method of persisting data across PHP pages, work based on files. You can change the session handler to be database based instead, but that's not RAM based, either.

As far as I can see, without changing your system on root level (e.g. to install memcached, or store session files on a RAM disk), this is not possible.

Upvotes: 4

Related Questions