Solved

PHP - Site Wide Values

Posted on 2012-03-29
11
322 Views
Last Modified: 2012-03-30
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
0
Comment
Question by:highlawn
  • 4
  • 3
  • 2
  • +1
11 Comments
 
LVL 82

Accepted Solution

by:
Dave Baldwin earned 167 total points
Comment Utility
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.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 167 total points
Comment Utility
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.
0
 
LVL 7

Assisted Solution

by:designatedinitializer
designatedinitializer earned 166 total points
Comment Utility
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.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
error_reporting(E_ALL);


// DEMONSTRATE HOW NOT TO USE SESSIONS


// A CLASS THAT ACCESS DATA IN THE SESSION ARRAY
class BugSession
{
    public function __construct($key, $value)
    {
        $_SESSION[$key] = $value;
    }
}


// THIS WILL CAPTURE THE OUTPUT BUFFERS
ob_start();

// SET SOMETHING IN THE UNSTARTED SESSION ARRAY - NO ERROR!
$_SESSION["Ray"] = "Paseur";

// CALL THE CLASS TO SET SOMETHING IN THE UNSTARTED SESSION ARRAY - NO ERROR!
$x = new bugSession('Dave', 'Baldwin');

// SHOW THE CONTENTS OF THE UNSTARTED SESSION ARRAY
echo "<br/>THE SESSION BEFORE SESSION_START() ";
var_dump($_SESSION);

// NOW START THE SESSION
session_start();

// SHOW THE CONTENTS OF THE STARTED SESSION ARRAY
echo "<br/>THE SESSION AFTER SESSION_START() ";
var_dump($_SESSION);

Open in new window

0
 

Author Comment

by:highlawn
Comment Utility
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?
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
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.
0
 

Author Comment

by:highlawn
Comment Utility
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.
0
 
LVL 7

Expert Comment

by:designatedinitializer
Comment Utility
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).
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
... an array called $gl_data
It's already there in PHP.  It's called $GLOBALS.
http://us.php.net/manual/en/reserved.variables.globals.php
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.
0
 

Author Comment

by:highlawn
Comment Utility
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 php.net "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
0
 

Author Closing Comment

by:highlawn
Comment Utility
All the replies were very useful and will assist me greatly.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

These days socially coordinated efforts have turned into a critical requirement for enterprises.
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now