multiple sessions on one web application - php

I know I can use $oldSession = session_name("mySessName"); to set the name of the session, which I do like so:
# FileName: sessionTest.php
$old_name = session_name("TEST");
session_start();
$_SESSION["hi"]="hi";
print_r($_SESSION);
I can even have another file: sessionTest1.php which contains the following:
# FileName: sessionTest.php
$old_name = session_name("TEST1");
session_start();
$_SESSION["Bar"]="bar";
print_r($_SESSION);
I can go back and forth between sessionTest.php and sessionTest1.php and the session will only have the corresponding variable.
The issue I am running into is suppose a different script already has a session started and then calls this file. What I am seeing is suppose I have:
session_name("other");
session_start();
$_SESSION["foo"] = "foo";
require_once "sessionTest.php";
print_r($_SESSION);
This is printing Array( "foo" => "foo", "hi" => "hi" ). Is there a way to end the previous session and start my session fresh. Note: I don't want to destroy the previous session as there may be valuable information in it.

what i do is make my SESSION 1 layer deeper then the standard. so i can just use that layer of the array.
some page:
<?php
$_SESSION['myApp1']['hi'] = "Hi";
?>
some other page:
<?php
$_SESSION['myApp2']['ciao'] = "Ciao";
?>
so when i want to see session vars on page 2 i just
<?php
echo "<pre>";
print_r($_SESSION['myApp2']);
echo "</pre>";
?>

use session_name before session_start.
PHP session_name
The session name is reset to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() or session_register() are called).
read this SO answer:
Multiple Sessions

Related

obscurity about session_destroy

i have searched and searched and read and read a lot about what exactly session_destroy does ! but no result at least for me ! first read the details below :
When a session is created (session_start) a file is created with a
unique identifier that is given to the user as a cookie, when
variables in the $_SESSION array are modified or added the temporary
file is updated with that information so that it can be used somewhere
else on the website.*
session_destroy* will delete this file, this is commonly done for when
a user logs out of your website so that the (now useless and
unnecessary) file isn't taking up space.
we know that session id is stored in session cookie and as the tutorials say , session destroy removes the session cookie file (that includes session_id ) so why when i started a new session it didn't generate a new id ! it makes me confused ! look at the example :
<?php
session_start();
echo session_id();
session_destroy();
session_start();
echo "---".session_id();
?>
result : l4k80dkrl5kd6cdlobhbu5s3i1---l4k80dkrl5kd6cdlobhbu5s3i1
so it gives me the session id same as the previous one .
so what does session_destroy really do !! ?
thanks in advance
From PHP documentation:
It does not unset any of the global variables associated with the
session, or unset the session cookie.
So after session_destroy() the cookie that holds the session id is still alive, and just the session file will be deleted. So start_session() tries to find the file for the session id in the cookie, and it fails of course, and it just creates a new empty file for that. So your id does not change.
If you really want to change that, try to delete the cookie.
You are almost correct about what you have said, BUT if you destroy the session and the script ends in PHP, thats the time file is deleted. If you just try to destroy and create it again, it uses the same file/session ID.
Its not only the file that is created, but also the file contains all the data you are storing in the session. Have a look at your session data in your server, its very interesting.
Update
More interesting things you can do. Write a PHP file
<?php
session_start();
sleep(29000);//delete the session after 29 seconds
session_destroy();
?>
Now have a look at the session file, it should be deleted after 20 seconds.
Do
<?php session_start(); ?>
and go to google chrome, and remove the cookie manually from there. The session won't be available anymore.
<?php session_destroy(); ?> will not destroy the cookies on the
client side. Next time you create a session, it will just use the same
old information. This is the prime reason of your question.
Do
file1:
<?php session_start(); $_SESSION['test'] = "A"; ?>
file2:
<?php session_start(); $_SESSION['test'] = "B"; ?>
resultFile:
<?php session_start(); echo $_SESSION['test']; ?>
Now from two computers, access your website with file1 on one computer and file2 on another. From google chrome, switch their cookie information and see how session A is assigned to B and B is assigned to A.

Fetching value stored in session on previous page with another session name using php

Here is my scenario.
I have 2 different pages with php
1). index.php page have session name declared as "session_one"
$some_session = session_name("session_one");
session_set_cookie_params(0, '/', '.domain.net');
session_start();
2). order.php page have session name declared as "sesson_random" (this is required to have another session name due to nature of implementation
$some_session = session_name("sesson_random");
session_set_cookie_params(0, '/', '.domain.net');
session_start();
now the issue that I am facing is that I have stored some values on index.php in session which I want to retrieve on order.php. I have tried many ways but unable to pass it.
Please note that I can not pass those values in query string of url.
Please help
You should be able to read the data from the other session, by restoring it before you open the new one. All you have to do is use the session_id function. I tested it with this code right here: (index.php)
<?php
session_name("session_one");
session_start();
$_SESSION["test"] = array("this is just a test");
print_r($_SESSION);
?>
Now, all you have to do is load the other session first and save the values into an array: (order.php)
<?php
if(isset($_COOKIE["session_one"])){
session_id($_COOKIE["session_one"]);
session_name("session_one");
}else{
session_name("session_one");
}
session_start();
$session = $_SESSION;
session_write_close();
print_r($session);
if(isset($_COOKIE["session_random"])){
session_id($_COOKIE["session_random"]);
session_name("session_random");
}else{
session_name("session_random");
}
session_start();
$_SESSION["other"] = array("this is another test");
print_r($_SESSION);
?>
The two sessions get combined. If you are not bothered by that, you should be good to go. Got some inspiration from here:
Can multiple independent $_SESSIONs be used in a single PHP script?

use a php variable in diffrent pages

I have two pages of php on the same folder , Im wondering what can I do to use that variable in another page like page2.php
page1.php
$variable = "Variable";
page2.php
//get $variable value from page1.php here
Any suggestions? Thank You
Use Sessions.
On page1.php:
session_start();
$_SESSION['var1'] = 'some text';
On Page2.php:
if(!isset($_SESSION)){
session_start();
}
echo $_SESSION['var1'];
You will get some test as output.
Use session variables.
Just write session_start() at the beginning of files to start a session and assign the session variables.
eg:
File-1
session_start();
$_SESSION['var'] = "var";
File-2
session_start();
if(isset($_SESSION['var']))
echo $_SESSION['var']; // will print "var"
You can use this throughout till the session destroyed. To destroy the session (may be on logout)-
if(isset($_SESSION['var']))
unset($_SESSION['var']);
To completely destroy the session-
session_destroy();
Or you can try constants like so:
constants.php
<?php
define("VARIABLE_1", "Hotdog");
?>
page2.php
<?php
include_once("constants.php");
echo VARIABLE_1;
// output == Hotdog
?>
Just include the constants php script in the pages you want to use the variables in.
Check PHP Sessions:
page1.php
session_start();
$_SESSION['variable'] = "Variable";
page2.php
session_start();
echo $_SESSION['variable']
You can require_once("page2.php") in page1.php
That will allow you to use variables in page 2 across page 1.
Alternatively, you can also use sessions.
session_start() starts a new session or resumes an existing session. Include this on the first line of both pages.
Session parameters are set using $_SESSION["parameter-name"] = "something";
You can use the variables anywhere in the script.
To terminate sessions, use session_destroy()
You can use Sessions to achieve this , also you should know about QueryStrings.
For example:
Navigate to another page say "location2.php?Variable=123" here ?Variable is your var and 123 is value.
And on location2.php you can get this by simply $_GET["Variable"];
This can be achieved in many ways. You can use php session, you can include a file where you create that variable, or you can define it as a consant.
All of that depends how complex is that problem and which suits you best in this case.

When setting a session with PHP, how do you make it global to the entire site?

I am creating a session and I want a variable to be available for the entire site, so for example:
Joe Soap lands on a page called red-widgets.php, - Joe's session variable is let's say 'red-widgets'. Joe then clicks on another page called blue-widgets.php. I would like the session variable to be still the original 'red-widgets'.
How can this be done with the url?
You are not limited to one session variable, you can have as many as you need.
session_start();
if ( !isset($_SESSION['widget']) ) {
$_SESSION['widget'] = 'i am changed only if there isnt already a widget session var';
}
$_SESSION['someOtherVar'] = 'i am being changed on every page';
Whenever a PHP page loads, just call session_start();. This will either 1. start a new session if one doesn't exist, or 2. restart whatever session was previously established. To make a new session variable, do this:
session_start(); // start or restart the session
$_SESSION['mySessionVariableName'] = "My session variable value.";
If you want to kill a session so that you can start a new one, you can do:
session_destroy();
If you want to erase all session variables but not kill the current session, you can do:
session_unset();
Simple:
on red-widgets.php:
session_start();
$_SESSION['red-widgets'] = 1;
on blue-widgets.php:
session_start();
if(!$_SESSION['red-widgets']){
//Joe weren't on red-widget.php, diffrent action here...
}

Can You Switch PHP Sessions In a Session?

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.

Categories