David Espart
David Espart

Reputation: 11780

PHP - How to share configuration data among sessions

I have a cluster of PHP hosts serving a small PHP script. The script retrieves an array of key/value pairs from the database at the beginning of the script, that are configuration values.

I would like to avoid the retrieving of these configuration data from the database for every request, in order to optimize.

My idea was that the script loads the data from the database only for the first request and it stores these variables into some kind of shared memory that is persistent among all sessions.

I've tried to use PHP global variables but they are all destroyed at the end of the script... Also, I would like to avoid using a config file because as I said I have more than one host serving the script and I'd like to store the data centralized.

Upvotes: 1

Views: 2125

Answers (4)

symcbean
symcbean

Reputation: 48367

...among sessions

rather implies that you are already using sessions - so why not just use a custom session handler?

You load the session data using the session id, and overload the config. Optionally you could set it up so you can call the read method and only return the config data without searching for conventional session data.

Probably the most efficient way to do this would be to run a daemon - that way you can keep the config data in PHP variables. There's a nice single threaded server implementation here.

Upvotes: 1

rasjani
rasjani

Reputation: 7970

Answer is memcached: http://memcached.org/

Its a sort thing that was meant to for this kind of scenarios and there are alot of good tutorials but official php documentation is a good starting point: http://php.net/manual/en/book.memcache.php

Upvotes: 0

Decko
Decko

Reputation: 19385

When I need to store small bits of data across scripts, I usually use apc

apc_add('config', array('a' => 'b'));

$config = apc_fetch('config');

Upvotes: 3

Knowledge Craving
Knowledge Craving

Reputation: 7993

You can keep this as:-

$_SESSION['_config_data']['index_1'] = 'value_1';
$_SESSION['_config_data']['index_2'] = 'value_2';
$_SESSION['_config_data']['index_3'] = 'value_3';
...

In this way, you will get all the configuration data stored in the session variable "$_SESSION['_config_data']".

But you need to check at the starting of the setting method, whether the session variable "$_SESSION['_config_data']" exists with some pre-filled data or not. If it is, then you don't need to set the configuration data for each page request.

Hope it helps.

Upvotes: 0

Related Questions