Can You Switch PHP Sessions In a Session? - php

I have two apps that I'm trying to unify. One was written by me and another is a CMS I am using. My authentication happens in the one I coded and I'd like my CMS to know that information. The problem is that the CMS uses one session name, and my app uses another. I don't want to make them use the same one due to possible namespace conflicts but I'd still like to get this information.
Is it possible to switch session names in the middle of a request? For example, doing something like this in the CMS:
//session_start already called by cms by here
$oldSession = session_name();
session_name("SESSION_NAME_OF_MY_APP");
session_start();
//get values needed
session_name($oldSession);
session_start();
Would something like this work? I can't find anything in the docs or on the web if something like this would work after session_start() has been called. Tips?
Baring this solution, I've been considering just developing a Web Service to get the information, but obviously just getting it from the session would be preferable as that information is already available.
Thanks!

Here is a working example how to switch between sessions:
session_id('my1session');
session_start();
echo ini_get('session.name').'<br>';
echo '------------------------<br>';
$_SESSION['value'] = 'Hello world!';
echo session_id().'<br>';
echo $_SESSION['value'].'<br>';
session_write_close();
session_id('my2session');
session_start();
$_SESSION['value'] = 'Buy world!';
echo '------------------------<br>';
echo session_id().'<br>';
echo $_SESSION['value'].'<br>';
session_write_close();
session_id('my1session');
session_start();
echo '------------------------<br>';
echo $_SESSION['value'];
Log will look like:
PHPSESSID
------------------------
my1session
Hello world!
------------------------
my2session
Buy world!
------------------------
Hello world!
So, as you can see, session variables saved and restored while changing session.

Note: the answer below is not correct, please don't use or vote up. I've left it here as a place for discussion
You solution should work (not that I ever tried something like that), except that you have to manually close the previous session before any call to session_name() as otherwise it will silently fail.
You can try something like this:
session_write_close();
$oldsession = session_name("MY_OTHER_APP_SESSION");
session_start();
$varIneed = $_SESSION['var-I-need'];
session_write_close();
session_name($oldsession);
session_start;
There's no need to actually mess with the session ID value, either through PHP session ID manipulation routines or through manual cookie mangling - PHP will take care of all that itself and you shouldn't mess with that.

I've been working on perfecting this and here is what I've come up with. I switch to a parent session using session names in my child apps and then back to my child app's session. The solution creates the parent session if it does not exist.
$current_session_id = session_id();
$current_session_name = session_name();
session_write_close();
$parent_session_name = 'NameOfParentSession';
// Does parent session exist?
if (isset($_COOKIE[$parent_session_name])) {
session_id($_COOKIE[$parent_session_name]);
session_name($parent_session_name);
session_start();
} else {
session_name($parent_session_name);
session_start();
$success = session_regenerate_id(true);
}
$parent_session_id = session_id();
// Do some stuff with the parent $_SESSION
// Switch back to app's session
session_write_close();
session_id($current_session_id);
session_name($current_session_name);
session_start();

session_regenerate _id()
The manual explains this pretty well but here's some example from the manual
session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";
print_r($_SESSION);

You should use session_id, you can use it to set / get the session id (or name).
So instead of using session_name (in your pseudo code), use session_id.

Zend_Session offers Namespacing for sessions.
Zend_Session_Namespace instances are
accessor objects for namespaced slices
of $_SESSION. The Zend_Session
component wraps the existing PHP
ext/session with an administration and
management interface, as well as
providing an API for
Zend_Session_Namespace to persist
session namespaces.
Zend_Session_Namespace provides a
standardized, object-oriented
interface for working with namespaces
persisted inside PHP's standard
session mechanism. Support exists for
both anonymous and authenticated
(e.g., "login") session namespaces.

It is possible. But I think you have to do the session handling yourself:
session_name('foo');
// start first session
session_start();
// …
// close first session
session_write_close();
session_name('bar');
// obtain session id for the second session
if (ini_get('session.use_cookies') && isset($_COOKIE[session_name()])) {
session_id($_COOKIE[session_naem()]);
} else if (ini_get('session.use_trans_sid') && !ini_get('session.use_only_cookies') && isset($_REQUEST[session_name()])) {
session_id($_REQUEST[session_naem()]);
}
// start second session
session_start();
// …
But note that you might do some of the other session handling things like cookie setting as well. I don’t know if PHP does this in this case too.

Related

Switch between sessions

Is there a way to switch between sessions in php?
I am storing a lot of data in php sessions and having many overflow issues, so now the first solution that came is subdivide session data somehow. Example:
//Uses session sector 1
switch_to_session('sector1');
$_SESSION['data1'] = 'tons of data'; //store data
//Uses session sector 2
switch_to_session('sector2');
$_SESSION['data1'] = 'another data';
//Return to sector 1
switch_to_session('sector1');
echo $_SESSION['data1']; //prints: 'tons of data'
Is that possible? Thanks in advance...
Although I suspect there is a better way of doing whatever it is that you are trying to do - in strict answer to your question : yes - you can switch sessions.
The trick is to save and close your existing session, then identify your new session and then start it.
Example:
<?php
session_start(); // start your first session
echo "My session ID is :".session_id();
$sess_id_1 = session_id(); // this is your current session ID
$sess_id_2 = $sess_id_1."_2"; // create a second session ID - you need this to identify the second session. NOTE : *must be **unique** *;
$_SESSION['somevar'] = "I am in session 1";
session_write_close(); // this closes and saves the data in session 1
session_id($sess_id_2); // identify that you want to go into the other session - this *must* come before the session_start
session_start(); // this will start your second session
echo "My session ID is :".session_id(); // this will be the session ID that you created (by appending the _2 onto the end of the original session ID
$_SESSION['somevar'] = "I am in session 2";
session_write_close(); // this closes and saves the data in session 2
session_id($sess_id_1); // heading back into session 1 by identifying the session I you want to use
session_start();
echo $_SESSION['somevar']; //will say "I am in session 1";
?>
Finally - putting it all together into the function you wanted :
<?php
function switch_to_session($session_id) {
if (isset($_SESSION)) { // if there is already a session running
session_write_close(); // save and close it
}
session_id($session_id); // set the session ID
session_start();
}
?>
That should do the trick.
Note : it is vital that your session IDs that are unique. If you do not, valuable user data is at risk.
To make life more complicated, you can also change your session handler (the way the session data is being stored) for each session that you switch to. If you are interfaceing with 3rd party code or systems, you may find that it is using a different session handler, and that can confuse matters. In this case you can also get/ set your session save handler and change that before starting the next session.
Not a direct answer to your question..
You are going about this all wrong, if you need to store that much data then you need to be using a different storage method - preferably a database, file or cache store.
In the session itself you should store the reference to the data - A file name, DB primary key or cache key.
AFAIK you cant 'switch' sessions.
So far I have not heard of such a thing exists.
Even though you have all the documentation here:
http://www.php.net/manual/en/book.session.php
I do not know what data you're trying to save in the session, but within the session you can put a "marker" with which you can split the data and list in PHP.
EXAMPLE:
<?php
session_start();
$_SESSION['data1'] = 'Hello my friend!|My friend is the best!';
$split=explode('|', $_SESSION['data1']);
echo $split[0].'<br>'; // Hello my friend!
echo $split[1]; // My friend is the best!
?>
http://www.w3schools.com/Php/php_sessions.asp

Using session variable to use info on different pages

i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.

PHP session variables life

Newbie question, but I'm wondering if I'm missing something elementary here.
If I register a session variable in a page - isn't this variable supposed to be accessible from another page on the same site?
First, I register a variable in the file session_var_register.php:
<?php
$_SESSION["myusername"] = 'user';
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
When I open this page, it writes:
Session var myusername is set to user
As expected.
Then I open another tab and another page, check_session_var.php:
<?php
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
This page is blank.
Isn't the point of a session variable that it should be accessible in the browser session, until the session is programatically destroyed or the browser closed?
I'm using IE 8 and Firefox 24, btw. Identical results.
You forgot
session_start()
On top, before using
$_SESSION
PS: Remember to call session_start() in every page you want to use $_SESSION.
The PHP docs state that you must call session_start() to start or resume a PHP session. This must be done before you try to access or use session variables. Read more here.
session_start();
Your session variables will be available on different pages of the same site but on top of each of these pages you must have at least:
session_start();
It works but not in all cases. You must also use the same session name (essentially a cookie name that stores id of your session) on all pages. Moreover cookies (which are essential (mostly) for sessions to work) may be made visible only in specific directory. So if for example you share the same host with other guys that use sessions too you do not want to see their variables and vice versa so you may want to have sth like that:
1) session_name( 'my_session_id' );
2) session_set_cookie_params( 0, '/my_dir', $_SERVER['HTTP_HOST'], false, true );
3) session_start();
You may also want to see your session variables on other servers and in such case custom session handlers may be useful. Take a day or two to implement yourself - great way to understand how sessions work hence I recommend.
Method
session_start();
Description
session_start() creates a session or resumes the current one based on a session identifier >passed via a GET or POST request, or passed via a cookie.
Usage in your case (and in the most of cases):
Put it before the $_SESSION usage.
Reference: session_start()
First Of all start session on that page
session_start();
your page like this way
<?php
session_start();
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>

What if PHP sessions are already started?

I'm making somewhat of a "module" that gets included into another unrelated PHP application. In my "module" I need to use sessions. However, I get the 'session has already been started...' exception. The application that my "module" is included into is starting the session. If I cannot disable sessions in this application, what are my options? I'd like to use Zend_Session, but it seems upon first glance that it is not possible. However, maybe there is another way? Any ideas?
Thanks!
With PHP’s session implementation, there can only be one session at a time. You can use session_id to check if there currently is a session:
if (session_id() === '') {
// no current session
}
Now if there is already an active session, you could end it with session_write_close, change the session ID’s name with session_name to avoid conflicts, start your session, and restore the old session when done:
$oldName = session_name();
if (session_id() !== '') {
session_write_close();
}
session_name('APPSID');
session_start();
// your session stuff …
session_write_close();
session_name($oldName);
session_start();
The only problem with this is that PHP’s session implementation does only send the session ID of the last started session back to the client. So you would need to set the transparent session ID (try output_add_rewrite_var) and/or session cookie (see setcookie) on your own.
Try setting a custom "name" parameter for your application.
The default is PHPSESSID. You can change it to PHPSESSID_MYAPP to avoid conflicts with the other app.
Add the following code before you want to use the Session feature:
#session_start();

PHP Login, Store Session Variables

Yo. I'm trying to make a simple login system in PHP and my problem is this: I don't really understand sessions.
Now, when I log a user in, I run session_register("user"); but I don't really understand what I'm up to. Does that session variable contain any identifiable information, so that I for example can get it out via $_SESSION["user"] or will I have to store the username in a separate variable? Thanks.
Let me bring you up to speed.
Call the function session_start(); in the beginning of your script (so it's executed every page call).
This makes sessions active/work for that page automagicly.
From that point on you can simply use the $_SESSION array to set values.
e.g.
$_SESSION['hello'] = 'world';
The next time the page loads (other request), this wil work/happen:
echo $_SESSION['hello']; //Echo's 'world'
To simply destroy one variable, unset that one:
unset($_SESSION['hello']);
To destroy the whole session (and alle the variables in it):
session_destroy();
This is all there is about the sessions basics.
The session is able to store any information you might find useful, so putting information in is up to you.
To try some things out, try the following and see for yourself:
<?php
session_start();
if(isset($_SESSION['foo']))
{
echo 'I found something in the session: ' . $_SESSION['foo'];
}
else
{
echo 'I found nothing, but I will store it now.';
$_SESSION['foo'] = 'This was a triumph.';
}
?>
Calling this site the first time should store the information, storing it the second time will print it out.
So yeah, you can basically put anything you like in the session, for instance a username.
Keep in mind, however, that the session dies as soon as the user closes his browser.
$_SESSION['user'] must be set to your user's name/id so that when you try to read it the next time, you'd be able to identify that user. For example:
login:
$_SESSION['user'] = some_user_id;
user area:
$user = $_SESSION['user'];
// extract the user from database, based on the $user variable
// do something

Categories