Can You Switch PHP Sessions In a Session?

Asked
Active3 hr before
Viewed126 times

9 Answers

sessionsessionsswitch
90%

You should use session_id, you can use it to set / get the session id (or name).,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.,So instead of using session_name (in your pseudo code), use session_id., This worked for me! Changing back to the original session is important because otherwise magic session handling code at the end will be ran and things get weird! – Roel van Duijnhoven Sep 18 '14 at 11:32

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!
load more v
88%

In addition to the normal set of configuration directives, a read_and_close option may also be provided. If set to true, this will result in the session being closed immediately after being read, thereby avoiding unnecessary locking if the session data won't be changed. , To use cookie-based sessions, session_start() must be called before outputting anything to the browser. , When session.use_trans_sid is enabled, the session_start() function will register an internal output handler for URL rewriting. , If provided, this is an associative array of options that will override the currently set session configuration directives. The keys should not include the session. prefix.

load more v
72%

Is it possible to switch session names in the middle of a request? For example, doing something like this in the CMS:,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.,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.,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.

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();
load more v
65%

So; Session variables hold information about one single user, and are available to all pages in one application.,Tip: If you need a permanent storage, you may want to store the data in a database.,A session is a way to store information (in variables) to be used across multiple pages.,Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

session_start();
["favcolor"] = "green";
75%

This is the method that you'll see most often, where a session is started by the session_start function.,That should give you the current session id. The session_id function is interesting in that it can also take one argument—a session id. If you want to replace the system-generated session id with your own, you can supply it to the first argument of the session_id function.,It’s important to note that the session_id function must be placed before the session_start call when you want to start a session with a custom session id.,If there’s a need to use sessions throughout your application, you can also opt in to starting a session automatically without using the session_start function.

This is the method that you'll see most often, where a session is started by the session_start function.

< ? php
// start a session
session_start();

// manipulate session variables
?
>
load more v
40%

Before we move on to how to start, update and end a session in PHP, let's learn a few realworld use of session.,NOTE: The function session_start() should be the first statement of the page, before any HTML tag.,Web applications which require a user to login, use session to store user information, so that on every webpage related information can be displayed to the user.,In simpler words, using the function session_start() we initialize the session, in which we can store information using the session variable $_SESSION.

Let's take an example, below we have a webpage with Php file named first_page.php

<?php
// start the session
session_start();

// set the session variable
$_SESSION["username"] = "iamabhishek";
$_SESSION["userid"] = "1";
?>

<html>

<body>

   <?php
    echo "Session variable is set.";
    ?>

   <a href="second_page.php">Go to Second Page</a>

</body>

</html>
load more v
22%

This line of code should come before any output is produced by the script!! The session_start() function either creates a new session, if one does not exist, or it continues an existing session. ,Create a PHP script that remembers the last time you visited the page and prints it out. If it is your first visit, it should welcome you to the site. Take a look at the date() function., Since your users might connect from different browsers on different computers, if you want to preserve some session information (e.g. a shopping cart started on one computer and continued on another), it may become necessary to store their session information in a file under your control so that when they log on you can recreate their session. , The session_id can be retrieved from your PHP script after session_start() has been run via:

To use sessions you must start your PHP script with:

session_start();

After the sessions has begun, you may access and use the $_SESSION global array and any changes to this array will survive between web page accesses! To set a value, treat this variable like you would any array.

$_SESSION['myvariable'] = 'myvalue';

Note: If you wanted to quickly output the entire contents of $_SESSION for debugging purposes, you can print out any associative array in a nice format with print_r() surrounded by <pre> tags.

<pre><?php print_r($_SESSION); ?></pre>

When working with session values, it is often useful to test whether a particular session variable exists. The easiest way to check to see if a variable exists is with isset().

if (isset($_SESSION['myvariable']) {
      echo $_SESSION['myvariable'];
   }

If you wish to delete a session variable, you should unset it (just like you can any variable in PHP):

unset($_SESSION['myvariable']);

If you want to remove the entire contents of the SESSION, you can destroy it.

session_destroy();

The session_id can be retrieved from your PHP script after session_start() has been run via:

$myid = session_id();

$mysession = session_encode();

session_decode($mysession);

ssh midn.cs.usna.edu

tail - f /
   var / log / apache2 / error.log

tail - f /
   var / log / apache2 / error.log | grep mAlpha

curl - v http: //midn.cs.usna.edu/~mAlpha/IT350/test.php
load more v
60%

In some cases, we may want to change a session variable to a different value.,In this step, we will replace the preset name variable in the details.php file, as shown below:,We can also use the following data to destroy the stored session variables:,In case you misspelled the session variables, PHP may not recognize the data you are referring to and, therefore, return the else statement.

<?php 
  //Starting session
  session_start();
?>

<!DOCTYPE html>
<html>

<body>
   <?php 
      //Using session variables to set a session
      $_SESSION["name"] = "Neema Muganga";
      $_SESSION["hobby"] = "writing";
      
      echo "Successfully set the session variables.";
    ?>
</body>

</html>
load more v
48%

In this tutorial you will learn how to store certain data on the server on a temporary basis using PHP session.,If you want to remove certain session data, simply unset the corresponding key of the $_SESSION associative array, as shown in the following example:,Tip: The session IDs are randomly generated by the PHP engine which is almost impossible to guess. Furthermore, because the session data is stored on the server, it doesn't have to be sent with every browser request.,Note: To access the session data in the same page there is no need to recreate the session since it has been already started on the top of the page.

< ? php
// Starting session
session_start(); ?
>
load more v

Other "session-sessions" queries related to "Can You Switch PHP Sessions In a Session?"