0

Is it possible to store php variables in some kind of cache, so they only need to be generated once, but available on every web page? Wihtout using POST, GET, COOKIES or SESSIONS

I have heaps of URL's stored as variabled which I want to keep handy.

I am aware of caching HTML, but id like to somehow cache php variables. Not sure there is a solution?

  • 3
    APC and memcache are both good for this. – Frank Farmer May 03 '11 at 02:21
  • possible duplicate of [Caching variables in PHP](http://stackoverflow.com/questions/5659574/caching-variables-in-php) – Frank Farmer May 03 '11 at 02:22
  • 2
    Just to clarify, do you want them generated once-per-visitor, once-per-boot, or generate once to use forever, for all visitors? I'm assuming you know that if it's a case of just sharing definitions you can include a common file in all pages. – Phil Lello May 03 '11 at 02:28

1 Answers1

1

I use the zend-server implementation of the php stack. Even the community edition comes with:

zend_shm_cache_fetch();
zend_shm_cache_store();
zend_disk_cache_fetch();
zend_disk_cache_store();

Things set in those variables live across script executions, and clean themselves up after a timeout specified on creation.

Complex variables are allowed, so you can store associative arrays and such without encoding them first.

I use them extensively.
The shm methods can store and retrieve 32k chunks in the 0.0005 second range.

To store the contents of the $results variable in a cache named blah, with a timeout of 120 seconds:

zend_shm_cache_store('blah',$results,120);

To later retrieve the contents of $results:

$results = zend_shm_cache_fetch('blah');
if ( $results === false ) { # It expired, or never existed..

Zend documentation on this: http://files.zend.com/help/Zend-Platform/zend_cache_functions.htm

You can turn up the amount of space you have in the zend server console. I think it defaults to like 32mb. I have mine at 256mb. You may need to reboot or clear your shared memory segments to make the larger space actually work though. Making it larger does make it slower though. It seems to be faster if you store large arrays of data instead of small individually referenced bits but ymmv.

Daren Schwenke
  • 5,428
  • 3
  • 29
  • 34