Zend - The PHP Company




Miscellaneous

Add Code


Store variables in shared memory. (ie cache variables)  

Type: code fragment
Added by: jcollins
Entered: 20/08/2000
Last modified: 08/12/1999
Rating: **** (5 votes)
Views: 8647
Save a variable to shared memory. In other words you are caching variables to shared memory and instantly making them available to all your php pages via shared memory.


<?php

# PHP implementation of AOLServer's shared memory! 
# Author: Jeremy Collins

$ShareKey  33241;         // Our *HOPEFULLY* unique key...
$ShareVar  1324;          // Our *HOPEFULLY* unique key for the variable...
$ShareSize 1024 1024;   // 1MB shared memory to start with...
                            // We'll dynamically allocate more if needed...

function ns_share($VariableName)
{
  global $
$VariableName;
  global 
$ShareKey$ShareSize$ShareVar;

  
# Get and lock a semaphore.
  
$sem sem_get($ShareKey);
  
sem_acquire($sem);

  
# Attach to our existing shared memory segment.
  
$shm shm_attach($ShareKey$ShareSize);
  
$InitArray shm_get_var($shm$ShareVar);

  
$InitArray[$VariableName] = $$VariableName;

  
shm_put_var($shm$ShareVar$InitArray);

  
shm_detach($shm);
}

function 
ns_share_init()
{
  global 
$ShareKey$ShareSize$ShareVar;

  
# Create a new empty shared memory segment, or
  # globalize the existing variables.
  
if(!file_exists("/tmp/.cache.$ShareKey"))
  {
    
# Get and lock the semaphore.
    
$sem sem_get($ShareKey);
    
sem_acquire($sem);

    
$shm shm_attach($ShareKey$ShareSize);
    
$InitArray["_INTERNAL_EMPTY_"] = "";

    
shm_put_var($shm$ShareVar$InitArray);
    
shm_detach($shm);

    
sem_release($sem);
    
touch("/tmp/.cache.$ShareKey");
  }
  else
  {
    
# Get and lock a semaphore.
    
$sem sem_get($ShareKey);
    
sem_acquire($sem);

    
# Attach to our existing shared memory segment.
    
$shm shm_attach($ShareKey);
    
$InitArray shm_get_var($shm$ShareVar);

    while(list(
$key$value) = each($InitArray))
      
$GLOBALS[$key] = $value;

    
shm_detach($shm);
  }

}

ns_share_init();

?>


Usage Example


Run the following code in a separate file.

<?php

include("ns_share.php");

$MyTest "Hello out there!";
ns_share("MyTest");

$NewTest "Another test";
ns_share("NewTest");

print 
"Inserted vars into memory.";

?>

Then run this code in another file.  Notice how you are able to access the variables stored from the other page!

<?php

include("ns_share.php");

function 
test()
{
  global 
$MyTest;

  print 
"Retrieving a variable from shared memory: $MyTest";

}

test();

?>


Rate This Script





Search



This Category All Categories