Using the PHP Session in WordPress

WordPress and Sessions

The WordPress platform is totally stateless and provides no support for the use of sessions outside of the cookie that keeps a user logged in.  This is a very good policy and helps keep your blog light and responsive.  Unfortunately there are times that a session might be convenient to hold some data between requests.  If you search online and in the WordPress forums you will find a lot of discussion of this and a few ideas that point in the correct direction.  

The best of these is Frank Verhoeven’s blog Post on this topic which is short and sweet and contains the basic idea.  The comments on this are the real gold.  What I’m providing here is a summary of the facts I’ve found in those comments and much other online study and experimentation.

Getting access to the session if you are not writing a plugin or theme

The simplest way to get access to the session is to add the following lines to wp-config.php before the call to wp-settings:

if (!session_id())
    session_start();

This is what Frank suggested and it works well if you want to get the session for some of your own code and register_globals isn’t set.

What about register_globals?

You’ll hear a lot of talk about the deprecated PHP option register_globals in php.ini and WordPress’s attempts to defeat its use with the wp_unregister_globals function in load.php. WordPress is correct in doing this, so don’t just comment out wp_unregister_globals.

If register_globals is set WordPress will clear all the globals that it are set. Calling session_start will set the $_SESSION global, so if you call it before wp-settiings is run and register_globals is set you will lose your session variables. In most cases this isn’t a problem, but your hosting provider may have turned that option on and you can’t turn it off.

If that’s the case, you can’t put the session_start in wp-config.php. You will need to put it in your code before you need the session. And if you put it elsewhere be sure to remove it from wp-config.php or you will lose your session.

But of course It’s a plugin that needs a session

You can’t put your session_start in wp-config.php if you are intending to distribute your code to others, since you have no access to it and your users might have register_globals set.  In that case you need to hook into an action that takes place after WordPress is loaded but before your code needs the session.  

You can hook into the “init” action, to do that you would add some code like this to your plugin or your theme’s functions.php:

add_action('init', 'myStartSession', 1);
function myStartSession() {
    if(!session_id()) {
        session_start();
    }
}

This code starts the session early in the initialization process, the 1 is the priority to cause this to run before other initialization. The session will be available once this has run.

One last piece in the puzzle

But it’s still missing a crucial piece.  The data stored in the session doesn’t go away when the user logs out or logs into a different account. For that you need to destroy the session.  And of course that requires a couple more hooks.  This results in the following code to start and destroy the session:

add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');

function myStartSession() {
    if(!session_id()) {
        session_start();
    }
}

function myEndSession() {
    session_destroy ();
}

Now the session is yours to use as you wish in your code

To save some data into the session

$_SESSION['myKey'] = "Some data I need later";

And to get that data out at a later time

if(isset($_SESSION['myKey'])) {
    $value = $_SESSION['myKey'];
} else {
    $value = '';
}

I hope this is of help to others who have faced this problem.

The following two tabs change content below.

Peter

Web Developer at Silver Maple Web
Peter is a partner and Web Designer and Developer on Silver Maple Web. Peter has been building websites since 1996. He has design experience and programming expertise in PHP, Java, APL, HTML, CSS, and Javascript.

Latest posts by Peter (see all)

35 thoughts on “Using the PHP Session in WordPress

  1. Man, this is driving me crazy.

    I developed some kind of shopping cart for my store in WordPress. It’s very simple and works wonderfully in all browsers, except for Firefox. I made a lot of research and found out that this sessions problem with WordPress was not only with me. Then I tried all the solutions that Google gave me, including the very same code in this post. No success.

    I can be sure that register_globals is set to off in my server, so i just commented the content of the wp_unregister_GLOBALS function out. Still no success.

    The most bizarre part of my drama is that, in my own pc, the shopping cart works like if I never had a problem with it. Every other computer fails in completing any order in Firefox, because the cart is always empty when it’s sent to the payment method.

    I hate the idea of messing with the WordPress code and tried to solve all problems in a clean way, but this is making me go berserk.

    Any idea?

  2. When trying to load a Web site, the following error is occurring:”Server Requirement Error: register_globals is disabled in your PHP configuration. This can be enabled in your php.ini configuration file or in the .htaccess file in your catalog directory.”Can you tell me exactly what needs to be done to fix? Not sure how to access php.ini. I can access .htaccess the contents of which are below.

  3. I just registered to say thanks for your post. I guess, it saved a lot of time!!! In addition, I couldn´t find wp_unregister_GLOBALS() in wp-settings.php. So the ones, using WP 3.1, can find the function in wp-includes/load.php.

  4. Thanks for the article. I’m trying the code in a plugin I set the session variables and the first page loaded after setting them works fine. But when next page loads after that they seem to be lost again.

    Specifically, I have a custom login plugin where user’s may register on a custom form, on completing the form session vars are set and they are redirected to a thank you page. On all pages I have a header widget injected with a short code. The short code function checks the session and renders a logged in or not logged in version.

    This works on the thank you page immediately after session vars are set, but any pages after that seem to lose the session vars.

    Anyone experienced something like this?

  5. Hello Peter,
    I’m pretty new to WordPress but have a bit of experience with PHP, but by no means an expert. I have built my own CMS system and have used SESSION a bit with them and am trying to get $_SESSION to work in order to detect a stream a user has come from within the site, but not having any luck. Here is what I am trying to do:

    I have 3 pages public, media, profession. Each page states an appropriate $_SESSION as being either
    $_SESSION['siteStream'] = ‘public’;
    $_SESSION['siteStream'] = ‘profession’; or
    $_SESSION['siteStream'] = ‘media’;

    On a fourth page I have the following:

    session_start();

    //define variable for detecting which stream user is in
    if(isset($_SESSION['siteStream']) ) {
    $siteStream = $_SESSION['siteStream'];
    }

    And in the body of fourth page to detect which stream the user has come from

    But for some reason it is always giving me ‘profession’ as the output. Can anybody advise as to what I could be doing wrong? I have tried all of what you’ve mentioned above but I think it’s all relative to a user being logged in?

  6. Being logged in shouldn’t matter. The session will exist from the time you first start it.

    I’m assuming a “stream” is a set of pages that relate to a particular kind of use. Check the code in each of the streams to see what is different about the “profession” stream. Try displaying the value of the $_SESSION array in each of the streams at the start of each request.

  7. Yes, a stream is a set of pages, as you say. There is nothing different on the code, on each of the stream pages, in the header, I have the following with the appropriate stream variable,
    $siteStream = ‘publicOrMediaOrProfession’;
    $_SESSION['siteStream'] = $siteStream;

    and do a test on the page of and it outputs the correct variable. But on the fourth page where I want this stream variable known, SESSION is not getting passed to it.

    I’ve also just installed your plugin Simple Session Support but this doesn’t seem to help either.

  8. The session_start() call is what makes the $_SESSION array global, you should also check that register_globals is not being used as this will wipe out your session. The session_start must be done in the wp_init hook, this will cause it to run before your code. The Simple Session Support plugin does this.

  9. Try adding this code to your theme’s functions.php, it should display “session testing=n” where n is the number of times it’s been called.

    function sessionTest() {
    if(!session_id())session_start();
    if (!isset($_SESSION['testing']))$_SESSION['testing'] = 0;
    else $_SESSION['testing'] = 1+$_SESSION['testing'];
    echo ‘session testing=’.$_SESSION['testing'].’
    ‘;
    }
    add_action(‘init’, ‘sessionTest’, 1);

    If it doesn’t display an increasing number then there is something wrong with session support on your system. Have you checked phpinfo to see if sessions are enabled? You can create a .php file containing:

    phpinfo();

    to display phpinfo, give it a non-obvious name and be sure to delete it after use as it’s a serious security breach.

  10. Thank you for your assistance Peter. I’m not able to access the php.ini file as it’s controlled by the host provider on a shared server, but a phpinfo page gave me this:

    register_globals Off Off
    Session Support enabled
    session.auto_start Off Off
    session.use_cookies On On
    session.use_only_cookies Off Off

    You can see the full readout here
    http://thewebsitedeveloper.co.nz/tempProject/sessionDetails.jpg

    So it’s telling me register_globals is off so that shouldn’t be causing a problem? Is the session.auto_start being Off causing a problem?

    I did try adding the function sessionTest but it resulted in turning the site into blank pages, no error message.

  11. The session config looks fine, and having register_globals off is good.

    When you get a WSOD (White Screen of Death) out of WordPress there is usually a syntax error in your code. That code works fine on my site, so I suspect something got lost in transfer. Sometimes empty lines after ?> will cause that, for that reason I never close the last php block. You might find some hint about the problem by looking in the log files.

    Do you have a local development system? If not you should set one up, either on a Linux machine or on your workstation using WAMP if you use Windows or by installing MySQL on a Mac, it already has PHP and Apache installed. On a local test system you will be able to easily sort all this out.

  12. Well the good news is that everything works perfectly on my local xammp build (even without your plugin). I guess the hard part now is to find out why it doesn’t work on a hosts server.
    Thanks for your help.

  13. The main difference I’ve spotted is that my local build has
    session.save_path \xampplite\tmp \xampplite\tmp
    The live host has
    session.save_path no value no value

    Does this mean that session is not actually being saved so is not available once the page setting session is left?

  14. My site is built based on WordPress, but I don’t want to use the WordPress built-in membership system, I’m trying to make a simple one, do you have any suggestion? ps. I am not php expert, this worrys me.

    • I’m not an expert of membership plugins, there are several favourites out there. One of the most popular is s2member. Your choice also depends on what your requirement is and what budget you have,

  15. I understood the wp_login and wp_logout hook part but what about if someone simply closes the website without even logging out properly. In such cases, how do I destroy users session data? Thanks.

  16. No, this is http, when someone leaves your site there is no way for you to know. The session will be destroyed when they close their browser.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *