Programming: November 2007 Archives

Handling PHP Sessions on Bengal/VH

| | Comments (0) | TrackBacks (0)

If you have always used the default settings for sessions in your PHP apps on Bengal, you might have awoken to a nice little surprise on Halloween when Division of IT implemented suPHP on the Bengal servers.

Before Halloween, if you didnt specify a session_save_path(), php would write to a default location as the Apache user. Which was just fine, because at the time, php was running as the Apache user. But once they implemented suPHP, php was now running as the owner of the application. With that, your php scripts, running as you, no longer had permission to write to the default directory (which if I remember correctly, was /tmp).

Division of IT has since placed an article in the KnowledgeBase, but I thought I would expand on it.

In your home directory on Bengal (at the same level as your www directory), there should now be a "session" directory. This is where you will need to have your php scripts store your session files. To do so, before any calls to session_start(), and on every page where you are going to be using sessions, you will need to use session_save_path('/path/to/your/session/');

Personally, I like to have my own function to handle sessions that I can call at the beginning of the page. That way, when I have to move servers (like from Bengal to VH), I dont have to go update my session path in every file (plus gives me the ability to do some other things that I will discuss later). So, if the path of my session directory is /users/p/gilzowp/session/ then I could set my function up like so:

[code]
/**
* Sets up the correct session save path, and initiates the session
*
* @return void
*/

function mySessionStart(){

    session_save_path('/users/p/gilzowp/session/');
    session_start();
}
[/code]

Now in each page where you want to use sessions, after you have included/required the file that contains your session function, you simply need to call mySessionStart();

Next, I'll discuss some problems with sessions and things we can do to get around those problems.