Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using session_name() in PHP - Cannot Access Data

When I use:

session_name( 'fObj' );
session_start();
$_SESSION['foo'] = 'bar';

Subsequently loading the page and running:

session_start();
print_r( $_SESSION );

doe not return the session data.

If I remove the session_name(); it works fine.

Does anyone know how to use sessions with a different session name?

UPDATE:

If I run the above code, as two page loads, and then change to:

session_name( 'fObj' );
session_start();
print_r( $_SESSION );

I can access the data. However, if it will only work if I first load the page without the line:

session_name( 'fObj' );
like image 239
Kohjah Breese Avatar asked Aug 22 '14 02:08

Kohjah Breese


3 Answers

John Robertson is correct, the statement he mentioned comes straight from the PHP manual (http://php.net/manual/en/function.session-name.php).

Your session name by default comes from the php.ini variable 'session.name', and this is generally set to 'PHPSESSID'. At each startup request time (as already mentioned) the session will be renamed to PHPSESSID unless you call session_name( 'fObj') before session_start() on every page, so page1:

<?php
  session_name( 'fObj' );
  session_start();

  $_SESSION['foo'] = 'bar';

page 2:

<?php
  session_name( 'fObj' );
  session_start();

  print_r($_SESSION);

Subsequently you can go to your php.ini settings and change the session.name variable from PHPSESSID to fObj and all of your created sessions will have a session name of fObj.

like image 160
Anth Bieb Avatar answered Oct 06 '22 15:10

Anth Bieb


In light of nwolybug's post I think this must be due to some environmental settings. I can get this to work via doing the following:

if( $_COOKIE['fObj'] )
{
    session_id( $_COOKIE['fObj'] );
    session_start();
}
var_dump( $_SESSION );
like image 35
Kohjah Breese Avatar answered Oct 06 '22 17:10

Kohjah Breese


I am able to get it working fine and returning SESSION data with the following code:

session_name( 'fObj' );
$_SESSION['foo'] = 'bar';

session_start();
print_r( $_SESSION );

If I run it with the second session_start(); It comes back with an error telling me a session is already started. If you are in dev, make sure to enable ERROR_ALL in php.ini. Make sure to turn it back off in production. A link to the php error reporting functions.

Update: Also works with: session_name( 'fObj' ); $_SESSION['foo'] = 'bar';

print_r( $_SESSION );

Using Ubuntu 14.04 LTS, PHP 5.5.9-1 (let me know if you need more system info to suss out the problem)

like image 36
nwolybug Avatar answered Oct 06 '22 17:10

nwolybug