Link to home
Start Free TrialLog in
Avatar of ClintonK
ClintonKFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How to run code once per session?

How can I run php code once for a Wordpress session. My site reads data from the database and stores it in arrays. At the moment I have functions that are called and each time they are called they load the array from the database which is rather a waste of resource. The data won't change for the duration of the session so it would be good to load up the arrays when the wordpress site is loaded.
Is this possible?
Avatar of Jan Louwerens
Jan Louwerens
Flag of United States of America image

How about just creating a cache for the data. Instead of loading from the database with each request, get the data from the cache. If the cache is not yet initialized, then load the data from the database.
Avatar of ClintonK

ASKER

Sounds like a good idea. Not something I thought was possible in php. Got any pointers as to where to get more info?
I'll admit I don't have a lot of experience personally using php, but maybe this link could help provide some useful information:

https://www.thesitewizard.com/php/sessions.shtml

just where you normally load the data from the database, load it from the session instead. If it's not in the session, then load it from the database and store it in the session.
Even if you store it in $_SESSION variables, it still gets loaded from disk each time the page runs.  While I do this for user or session specific data, I get it from the database for all other purposes.  The 'arrays' you're talking about are not going to stay in memory between page requests.  That is especially true if you are on shared hosting.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I've created a function for each of the arrays and the site now appears to be far more responsive. The code is also a lot easier to read now too.
Many thanks
You are welcome.