Session Variable in WordPress

Web application is stateless, which means once the request is fulfilled, all variables involved during the request will be gone. Most of the time, programmer needs to be able to access data that was set during previous session, and for this, there are many methods that can be used, one of them is using session.

With session, data that is used during a request can be stored inside a text file on web server. When needed in different request, this data can be read so it will be available to be used during this new request.

The text file used to store the session is unique, meaning it is tied to the browser session. As long as you are using the same browser session, the file will be the same. However, once you close the browser, next time you access the same information, you will be assigned different session file.

In order for the web server to know which session file belong to which browser session, the web server sends a cookie which contains the name of the session. This cookie is set to expire at the end of the session. That is why when you restart your browser, you will be assigned different session file. Figure 1 shows the cookie that contains the information about the session.

Session cookie

Figure 1. Session cookie

The session file is not automatically created by the web server. You need to tell the web server that you want to create the file and using the session. In order to do this, in PHP you need to use function session_start. After calling this function, the web server will check first if the browser sends the session cookie. If yes, the web server will check if it has the session file associated with the value in that session cookie. If yes, that session file will be used, if not, a new session file will be created. If the browser does not send the session cookie, a new file will be created and the web server will send the session cookie to the browser so on the next request, the browser can send that session cookie back.

Working with session in WordPress

WordPress does not use session so the session is not automatically initialized. To use session in WordPress, you need to initialize the session manually. Common place to initialize the session in WordPress in to put the initialization code in wp-config.php file. This file is unique to the WordPress installation so it will not be overwritten during WordPress upgrade.

So, to use session in WordPress, you can put the following code inside your wp-config.php file anywhere before the line that has require_once(ABSPATH . ‘wp-settings.php’); code. Usually on top after the <?php line should be a good place.

Listing 1:

session_start();

If your PHP installation does not have register_global enabled, the above code should allow you to use session, however, if it does, you will not be able to get the data that was set in previous request. This is because WordPress will destroy all data contained inside session variable when it does the initialization.

If you look the last line of your wp-config.php file, after reading the content of your wp-config.php file, WordPress then loads file wp-includes/wp-settings.php. Near the top of this file, WordPress calls function wp_unregister_GLOBALS(). Inside this function (inside wp-includes/load.php), as shown in listing 2, if register_global is enabled, the content of the session variable will be deleted. So, how can we use the session in this situation?

Listing 2:

function wp_unregister_GLOBALS() {
	if ( !ini_get( 'register_globals' ) )
		return;

if ( isset( $_REQUEST['GLOBALS'] ) )
		die( /*WP_I18N_GLOBALS_OVERWRITE*/
			'GLOBALS overwrite attempt detected'
			/*/WP_I18N_GLOBALS_OVERWRITE*/ );

// 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] );
		}
}

Fortunately, almost all the processes that WordPress does up until it calls function $wp->init(); (inside wp-includes/wp-settings.php) relates to WordPress initialization. We usually do not need to do anything up until this point. After calling that function, WordPress calls function do_action( ‘init’ );, which allows plugins to initialize, widgets to be loaded, etc. If your web server has register_global enabled, you can use this opportunity to initialize the session. Because we do the initialization after the call of function wp_unregister_GLOBALS(), the session variable will not be deleted.

However, if we initialize the session during this time, what if we need the session for one of our plugin? How can we be sure that the session is initialized before the initialization of the plugin that uses the session?

When adding a hook, WordPress allows us to put priority. So, to make sure that the session is initialized before the initialization of other plugins or widgets, when we add our hook for session initialization, make sure that it has higher priority. To do so, we can add the following code inside your theme’s function.php file.

Listing 3:

function kana_init_session()
{
	session_start();
}

add_action('init', 'kana_init_session', 1);

In this code, we put 1 as the priority number to make sure that it will be called before any plugins and widgets initialization (usually has number 10).

Post a Comment

Leave your comment below
The comment is moderated. Only comments related to the post will be accepted.
Your name
Email address
Your comment

Read Comments 9 Comment feed

  • I haven’t been able to test this for myself yet (my web hosts have sensibly turned register_globals off) but listing 3 certainly looks a wonderfully elegant solution to this bugbear. Thanks!

  • I used Listing 3, using the init hook, on 3.2.1. It works like a charm. Thanks.

  • Hello. I have do it but it doesn´t work with a link like this:
    http://localhost/wordpress/carro.php?id=1&action=add

    any idea? thanks in advance and thanks for the tip

  • Great it Works. Thanks You Saved Me…….

  • Please check the solution here it may can help you

    http://thedigilife.com/wordpress-how-to-set-session-custom-variable-while-login/

  • I have checked the register global by uploading phpinfo.
    it is showing register global ON. i tried all the method mention above but it is not working. Can you help ?

  • I have successfully set the session and can echo the number of my session to confirm. I am having problems echoing the session id in a link. I am using shortcode php exec.

  • Related issue:
    So if you programatically signon using wpsignon, does this destroy the session? It seems to make sense… sessions probably SHOULD be destroyed at signon. I have a signon plugin that seems to destroy the session, but I need data from the session to go from the unsigned in state, to the signed in state. Any ideas how to preserve session THROUGH the process of signing on?

  • Listing 3 works for wordpress 3.5.2.

    Thank you very much.

Printed:
Beta
You can get this information from:
http://www.kanasolution.com/2011/01/session-variable-in-wordpress/
Close this window
Email This Information
To send the message, please fill the form below
Email To
Subject
Message
Your Email
Validation

Please enter the text on the following image in the verification box below. Click here if you cannot read the text. All alphabets are in upper case.

Verification image