tags:

views:

278

answers:

4

I run foo.com. I have two different applications that live in foo.com: one is foo.com/bar, and the other is foo.com/example. I use sessions to track information about the user while they're logged in, but if the user goes from foo.com/bar to foo.com/example, foo.com/example sees the session the user started from foo.com/bar and uses that information. My question is, how can I have two different sessions going for each directory at the same time?

A: 

You may be able to use session_set_cookie_params to set the domain and folder for the session to be saved under. IE:

// Used on foo.com/example
session_set_cookie_params(86400, '/example');

// Used on foo.com/bar
session_set_cookie_params(86400, '/bar');
Steven Surowiec
This doesn't appear to work; I've tried it before (and just now again) without success. It might have to do with my global php.ini settings.
Matthew
You need to add trailing backslash to path. Without it it will certainly not work.
Anti Veeranna
If you have access to the php.ini you could try setting the 'session.cookie_path ' parameter directly as that's what this function is supposed to override. You could also use ini_set() if you don't have access to the php.ini file.
Steven Surowiec
+3  A: 

You could also use the same session but change the variable names that you look for.

Edit: Sorry this doesn't answer your question but gives an alternative solution.

This seems to be the best solution. Thanks.
Matthew
Thanks Matthew: Remember if it answers your question, remember to mark it as 'The Answer' :)
A: 

Another solution is to effectively create a namespace within your session by pre-pending all session values from foo.com/bar with "bar_" and foo.com/example with "example_".

The way you can keep this from being tedious is to abstract this functionality into a function or class method. For example:

function set_session_value($key, $value) {

  //figure out which prefix to use by checking the current working 
  //directory, or whatever method you like. set $prefix equal to
  // "bar_" or "example_".

  $_SESSION[$prefix . $key] = $value;
}

Then get your values with a matching function.

The main advantage of this is that you don't have to think about what variable names you're using in /example while programming in /bar. The other is that if you decide to change how you are storing session values, you can easily change everything in one place.

eryno
+2  A: 

You should call session_name before calling session_start. This sets the name of the cookie used to identify the session (by default this is PHPSESSID).

Use a different name for each application. You shouldn't have to mess with the variables inside the session.

Craig
+1: This really is the best way of keeping application sessions separate.
R. Bemrose