Session setup

from the Artful MySQL Tips List


PHP names a session PHPSESSID unless a different session name is passed via session_name(). You might think this is OK for scripts running in non-tabbed browsers, but tabbed browser pages running simultaneously can see one another's session data if they share a session name. That's probably not what you have in mind. Here is a simple solution for the problem:

1. On the far side of a secure login--that is, after the user is authenticated--have the first session-enabled script of your PHP application require_once( 'session_start.php' ), which assigns a unique microtime-based name to a session before starting it:


<?php

// session_start.php

ini_set"session.gc_maxlifetime"1800 );

$session_name 'sess' str_replace"."""microtime(true));

session_name$session_name );

session_start();

?>



2. In every other session-enabled page of your app, require_once('session_continue.php'):


<?php

// session_continue.php

if( isset( $_GET['_sess'] )) $session_name $_GET['_sess'];

else if( isset( 
$_POST['_sess'] )) $session_name $_POST['_sess'];

else die( 
"Session configuration error<br>\n" );

session_name$session_name );

session_start();

?>



3. Keep both these scripts outside the web document directory tree, for example in PHP_INSTALL_DIR/includes.

4. When calling a page that needs session data, pass the session name in the form, eg:


printf("<INPUT type='hidden' name='_sess' value='%s'>\n", $session_name);



or if there is no form, specify the session name in the URL, eg:


header( "Location: pagetocall.php?_sess=" . session_name() );



As you see in the code, session_continue.php will pick up the session name.

Return to the Artful MySQL Tips page