WordPress does not use sessions to hold any data being that it is a stateless application. This makes it quite a problem for tasks like a shopping cart, which requires data(the user’s selected product) to be remembered from one page to the next. This means that if you want to use PHP sessions in your plugins or custom modifications of WordPress you will need to do some custom coding.
Luckily the fix is a simple one that anyone can handle! You only need to do a little hacking to enable sessions within WordPress.
A session is a combination of a server-side file containing all the data you wish to store, and a client-side cookie containing a reference to the server data. The file and the client-side cookie are created using the function session_start() – it has no parameters, but informs the server that sessions are going to be used.
When you call session_start(), PHP will check to see whether the visitor sent a session cookie – if it did, PHP will load the session data. Otherwise, PHP will create a new session file on the server, and send an ID back to the visitor to associate the visitor with the new file. Because each visitor has their own data locked away in their unique session file, you need to call session_start() before you try to read session variables – failing to do so will mean that you simply will not have access to their data. Furthermore, as session_start() needs to send the reference cookie to the user’s computer, you need to have it before the body of your web page – even before any spaces.
The WordPress Fix For $_SESSION Variables
So in order to activate session variables within your WordPress installation the only thing you have to do is call session_start(); before any output is send to the client. Normally upgrading your WordPress installation will replace all files, so we will want to install the code within our site theme to avoid the changes from being lost.
We will add the next lines of code to our functions.php file within our theme:
if ( !session_id() )
add_action( 'init', 'session_start' );
It is best place to add these lines is at the top of functions.php, immediately after the php start tag (<?php).
If your server is currently running register_globals on you will also need to modify a function named wp_unregister_GLOBALS and can be found in your wp-settings.php file located in the root directory of the WordPress install. The code you are looking for is located around line 39:
$noUnset = array(‘GLOBALS’, ‘_GET’, ‘_POST’, ‘_COOKIE’, ‘_REQUEST’, ‘_SERVER’, ‘_ENV’, ‘_FILES’, ‘table_prefix’);
To allow sessions you simply have to insert _SESSION into the array. The final code will be:
$noUnset = array(‘_SESSION’,'GLOBALS’, ‘_GET’, ‘_POST’, ‘_COOKIE’, ‘_REQUEST’, ‘_SERVER’, ‘_ENV’, ‘_FILES’, ‘table_prefix’);
Sessions are now enabled on your WordPress blog! You can now use PHP sessions on your WordPress plugins or custom modifications.