How To Use Shared Memory in PHP

By Angsuman Chakraborty, Gaea News Network
Tuesday, November 13, 2007

PHP supports shared memory which can be used to store and retrieve data across processes. This is also another alternative way to communicate between php scripts. Normally shared memory is used for caching frequently used data in memory for php scripts on the same server. Let’s see how we can use shared memory with a simple example.

How to create PHP shared memory and save a variable (array)

Here is a sample code with comments:

$key = 'mykey'; // Key to store data with
//Returns System V IPC key; 'My test' should be replaced by the pathname of an existing file
// as per manual. I found that even a non-existent file works fine.
// The second argument is project identifier; a single character of your choice
$shm_key = ftok('My test','P');
$data =  shm_attach($shm_key); // Pointer to shared memory
// Sample data to store
$test = array("hello","angsuman","chakraborty");
shm_put_var($data,$inmem,$test); // Save the data in shared memory
print_r(shm_get_var($data,$mykey)); // Print the saved data
shm_detach($data); // Disconnects from shared memory segment; the data remains intact

How to fetch data from shared memory in PHP

$key = 'mykey';
$shm_key = ftok('My test','P');
$data =  shm_attach($shm_key);

1. The code has been tested on Linux only.
2. The arguments to ftok must be same to access the same shared memory from multiple scripts. For use in multiple processes within the same script file use __FILE__ as the first argument to ftok().

March 15, 2010: 12:17 pm

Your variables $inmem and $mykey are undefined… and should be the integer key for the variable to store… so basicly they’re evaluating as the integer zero, but using undefined variables(and not even the same one, for the first example) makes the code a bit untransparent ;)

… also the $key variable is never used for anything..

June 14, 2008: 12:21 pm

WordPress 2.5.1 screwed up my code. It is back again. Please refresh the page.

June 14, 2008: 12:16 pm

Thanks. I consider myself more as a Java developer :)

June 14, 2008: 11:48 am

where is the code? I tried opening the page in both Firefox and IE, and code examples seem to be missing ?

February 20, 2008: 3:26 am

this is wonderful code and i will test this under my system

November 13, 2007: 2:53 pm

It’s fantastic to see a PHP programmer who pays close attention to how much memory they’re using.

November 13, 2007: 12:05 pm

This was an interesting tutorial, nicely done I will have a go at trying this for my self.

Lamonte Harris

will not be displayed