How To Use Shared Memory in PHPBy 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); print_r(shm_get_var($data,$mykey)); shm_detach($data);
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().