PHP - Site Wide Values

Firstly, I make use of .ini files on the server (located out of public reach) and read these with my PHP scripts. The main reason is to get the database parameters for that site so that I can connect.

Sometimes though, there are sites where there are several settings that need maintaining and for these, I put some in the ini file but store the rest on the database. These parameters are then used throughout the site to tailor what the user sees.

I tend to write my sites using the MVC design pattern - having a main controller (usually index.php) that does all the necessary pre and post amble and then the rest of its role is purely to send you off to the correct scripts (MVC) for the page in question.

The vast majority of the sites are written using PHP classes and some of these are common across many sites - for example, I have a login/logout class and an SQL abstraction class. The classes are tailored to the site via site specific css.

All of which I am sure is fairly standard for most people.

My question concerns the storage of the site parameters which I often want available to every class in the site - I'm sure I could be more restrictive, but it is easier to store them all in an array and make that available.

To my mind (knowledge) there are three options (maybe you know of more!) to do this:

1. Standard array that you pass to the class constructor - or to each function
2. Global array using the global keyword in each class/function
3. The $_session array - automatically available for all

So, what do people think? Firstly, do you agree that the concept is a valid one or are there better ways to achieve the requirement? Secondly, which of the above gets your vote - or something else - as the mechanism to implement the requirement?

Just for clarities sake - I guess there are two questions here! One about the use of .ini files to provide the pre-database connection parameters and then once you have your parameters (from either .ini or the database) how to pass them around the site.

I should perhaps say that if an error is detected then my error and exception handlers log these and also dump the entire array of site settings in force at that time to the error log so I can see what was going on at the time.

Many Thanks
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
Most people put the 'ini' files inside PHP files so that they can't be read by outsiders.  They use "include 'config.ini.php';" for example.

The $_SESSION array is available only to the current session started by session_start().  It is not supposed to be accessible by all users.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
My thoughts interspersed below...

1. Standard array that you pass to the class constructor - or to each function
This would seem to proliferate a lot of copies of these arrays.

2. Global array using the global keyword in each class/function
I would avoid the global keyword - it invites variable name collisions.  And if you forget it once, you're into a nasty debugging cycle involving variable scope.  Besides, there is the $GLOBALS array for storing global information within the life of the request.

3. The $_session array - automatically available for all
I am guessing you mean $_SESSION (PHP var names are case-sensitive) that allows values to persist across requests.  I think of the session in much the same way I think of $GLOBALS.  It's a good place to put global stuff that you want to have available to every scope and namespace.
Yeah, ini files like you already use for pure initialization is the most suited.

Regarding those other options you put on the database... I would go about it this way:
(1. First, setup auto class loader.)
2. Create a special class for getting those settings from the database using a singleton pattern and caching.

Anywhere you need to get those settings from the database, you just instantiate this special class.

Of course you can use session vars, but IMHO that's not the most advisable way to go about it because (at least, from a purely theoretical point of view) your settings have a wider usage/purpose scope than the session mechanism.
In other words, your settings are functionally decoupled from the sessions mechanism, so their implementation should also be decoupled.
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Ray PaseurCommented:
Sidebar note... $_SESSION is a superglobal available in every scope and namespace.  And it is also persistent across requests, but only if you use session_start() correctly.  Unfortunately  $_SESSION IS NOT IMMUTABLE irrespective of whether you have issued session_start().  Install this script and run it.  If I designed PHP, any access to $_SESSION before the completion of session_start() would throw a fatal error!
<?php // RAY_session_error.php


class BugSession
    public function __construct($key, $value)
        $_SESSION[$key] = $value;


$_SESSION["Ray"] = "Paseur";

$x = new bugSession('Dave', 'Baldwin');




Open in new window

highlawnAuthor Commented:
OK - Many thanks for the tips. It's always good to get reasoned input from people who know more!

Could I just ask what Dave means by:

"The $_SESSION array is available only to the current session started by session_start().  It is not supposed to be accessible by all users."

I'm confused by the reference to users. I understand the need to issue a session_start prior to using the array.

WRT to Ray's first reply - Just to clarify that you can insert items into $GLOBALS? I always thought that you couldn't (in that it was automatically populated - presumably by use of the global keyword??) and so I use $_SESSION as my choice of storage for these things.

When I have uses the global keyword, I always prefix the variable with $gl which helps with the variable clash problem. In fact I use an array called $gl_data and all the site settings are entries within that array.

So, to recap:

1. The use of .ini files is supported/encouraged. And thanks to Dave for the hiding tip.
2. The use of a super global facility is generally supported but with one vote for using a class to extract each time (if I have read correctly) - will that not have a performance overhead? I always though read what you need once, store it all in memory and use from there was quicker.
3. Ray's warning about PHP not issuing an error if you load $_SESSION before issuing a session_start is noted.

Anything else?
Dave BaldwinFixer of ProblemsCommented:
I was trying to say that $_SESSION arrays are not shared.  'session_start()' creates a unique session id for each new user the first time they load that page.  A $_SESSION array with that unique id is created at that time. On each successive page with session_start() that the same user accesses, the $_SESSION array with that unique id is loaded.  Different users (with different session ids) are not supposed to be able to see what is in the $_SESSION arrays created for other users.
highlawnAuthor Commented:
Aah, yes - of course. I understand what you mean now. Thanks for the clarification. So, in essence, if we store all the site settings details in $_SESSION - we are effectively storing them "N" times - where "N" is the number of active users.

Perhaps a good reason NOT to use $_SESSION for this purpose.
Like I said before, you should decouple your global vars from session vars, as those are two different concepts.
Session vars should be used for their intended purpose which is maintaining state across page loads of the same session ("session" being an entity defined by the trinity useragent-ip-timeframe).
Ray PaseurCommented:
... an array called $gl_data
It's already there in PHP.  It's called $GLOBALS.
if we store all the site settings details in $_SESSION - we are effectively storing them "N" times - where "N" is the number of active users.
Yes.  It is equally true that when a client visits your site you are loading all of the PHP scripts.  The actual data required for the site setting details is likely to be quite small in the cosmic scheme of things.  I wouldn't worry about it.  But I also would only use the session for the things that are "stateful" for the individual client.  Maybe I can try to give you an example.

Let's say a client logs in.  Her status should be reflected in $_SESSION.  Let's say you decide that the site should produce orange output for error messages.  That kind of thing would go into a site-wide setting instead of $_SESSION.
highlawnAuthor Commented:
I didn't realise you could actually store your own data in $GLOBALS - I thought it was a system array, if you like, that stored details of global variables.

From "An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array."

That and the fact it was different to the other super globals in that it has no underscore...

Now I understand, I will use it.

And thanks - yes, I understand the stateful/stateless concepts.

So, thanks to everyone who has passed on some of their knowledge and I can see not other decent option than to split the points to everyone.

Kind Regards
highlawnAuthor Commented:
All the replies were very useful and will assist me greatly.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.