I’m wondering why WordPress does not support sessions and many people out there claim that putting the following code in functions.php might not be a good idea (it in fact works for me but returns PHP warnings, too):
function cp_admin_init() {
if (!session_id())
session_start();
}
add_action(‘init’, ‘cp_admin_init’);
Is it good idea to enable sessions in WordPress? What would be the correct way to do this?
The reason for not working $_SESSIONS
in WP Core:
The thing WordPress is doing with sessions is burdened inside ~/wp-includes/load.php
.
The responsible function for resetting the $_SESSION
to null
is wp_unregister_GLOBALS()
. So in case you really need it, you’ll have to turn register_globals
off in your php.ini
file.
/**
* Turn register globals off.
*
* @access private
* @since 2.1.0
* @return null Will return null if register_globals PHP directive was disabled
*/
function wp_unregister_GLOBALS() {
if ( !ini_get( 'register_globals' ) )
return;
if ( isset( $_REQUEST['GLOBALS'] ) )
die( 'GLOBALS overwrite attempt detected' );
// Variables that shouldn't be unset
$no_unset = array( 'GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES', 'table_prefix' );
$input = array_merge( $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset( $_SESSION ) && is_array( $_SESSION ) ? $_SESSION : array() );
foreach ( $input as $k => $v )
if ( !in_array( $k, $no_unset ) && isset( $GLOBALS[$k] ) ) {
$GLOBALS[$k] = null;
unset( $GLOBALS[$k] );
}
}
The idea behind it?
Also of note, is that technically there is no real need for sessions, there are always other avenues. Sessions rely on a session ID to validate and provide continuance, but these can be intercepted/predicted/stolen, at which point someone can impersonate you
– by @TomJNowell in the comments.