Wordpress

Session variables in Wordpress

For three days I had nearly despaired when I tried to extend a Wordpress site with a self-written login script. Everything worked properly on my local server, but as soon as I had uploaded it, the session variables didn’t seem to be passed any more: after the login, I stayed logged in for only one more click and then got logged out again.

After several unsuccessful Google searches (with the wisdom of hindsight it’s quite easy to google, but try and find something about this issue without reading any further than this) I found the reason at last, namely the function wp_unregister_GLOBALS() inside the file wp-settings.php. Here it is:

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
    $noUnset = 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, $noUnset) && isset($GLOBALS[$k]) ) {
                $GLOBALS[$k] = NULL;
                unset($GLOBALS[$k]);
            }
}

What does this function do?

  • Line 27/28:
    If register_globals is not activated in the PHP settings of the web server, it won’t do anything at all (which explains the different behaviours of my script on my local and the live server). If, however, register_globals is active, it proceeds as follows:
    • Line 34:
      As the comment already says, all global variables listed here will not be reset. As you can see, $_SESSION is not being mentioned!
    • Line 36–41:
      Now, all global variables are being shifted and deleted one by one.

In short: If register_globals is activated, $_SESSION will be deleted on every single page view. No surprise that we can’t get at our session variables any more!

What’s it all about?

Well, for one thing, Wordpress assumes that it’s meant to take care of the complete site – after all it is some kind of content management system. And that includes the administration of all variables as well.

What’s much more important though, is the fact, that the use of register_globals has been deprecated for a long time and the feature will even be completely removed in PHP 6. Today, it is strongly recommended not to use these kind of variables, because they involve safety hazards. So, Wordpress is obviously trying to imitate the behaviour of a deactivated register_globals in order to ensure safety and avoid potential variable conflicts.

Remedy

After having solved this riddle, the solution was perfectly obvious: I have to deactivate register_globals on the web server, so Wordpress wouldn’t even need to execute that stupid function. For this purpose, simply place a text file called php.ini inside your Wordpress directory, containing the following line:

register_globals Off

Further information on the subject can be found on php.net:

Leave a comment Arrow

  1. 12th December, 2008

    ubergoober UNITED STATES

    Nice… was racking my brain for the same damn thing. I’d found the wp_unregister_GLOBALS function and was 1 step behind the resolution before I decided to google what others have done to tweak this function.

    I updated my php.ini and whammo.. working like a charm.. thanks for your post.

  2. 21st January, 2009

    Satranc TURKEY

    I think we must find a solution without register globals.

    Thanks.

  3. 21st January, 2009

    Ginchen GERMANY

    Well, if you really want to make it work with register_globals on (which you shouldn’t, because it’s unsafe and allows for code injections!), you could simply edit line 34 and add $_SESSION to it, so it looks like this:

    33
    34
    
    // Variables that shouldn't be unset
        $noUnset = array('_SESSION', 'GLOBALS', '_GET', ... );

    After that, session variables should not be unset anymore.

  4. 22nd January, 2009

    Satranc TURKEY

    Hi Ginchen,
    Is it normal to use cookies? or is there a way to store global variables?
    I am working on a register script which sets special roles. I am trying to build this without modify the wordpress files. I need to store clicked button’s value. Like – freelancer, firm,… After this I can use filters for setting the specified role.

  5. 22nd January, 2009

    Ginchen GERMANY

    If you allow users to register anyway, you could also save this information in a database, so it will be available forever. You can do database queries by using the wordpress database ID saved in $wpdb.

    If you only need the data during the registration process, Cookies would be okay, too. Or you could even pass the information to the next page using $_GET.

  6. 5th April, 2009

    Caner TURKEY

    Hallo Ginchen,

    Danke für die Info. ;)

    Du hast mir das Leben gerettet. :D

    Grüsse aus Antalya
    Caner

  7. 12th May, 2009

    tkm UNITED KINGDOM

    Thank you so much for sharing this!! This solved a number of problems that I was experiencing. I can now get a proper nights rest.

  8. 26th May, 2009

    KRL SPAIN

    Im was debuging for hours before find this, thanks a lot, you rock!

  9. 17th June, 2009

    Kristina CANADA

    or you add _SESSION in the noUnset array of that function….

  10. 17th June, 2009

    Ginchen GERMANY

    Well, that’s what I just suggested to Satranc in the third comment… ;) But it is not a good solution. Hacking the Wordpress core files is never a good solution.

  11. 17th June, 2009

    Ashish INDIA

    Hi,

    I done same thing as you suggested.i set register globlas off in php.ini.but i am still facing problem.
    i also add _SESSION in $noUnset array but not getting session on next page

    please help it’s urgent

  12. 17th June, 2009

    Ginchen GERMANY

    It’s hard to tell what the problem is without seeing the code – what file do you want use the session variables in? Maybe you could post a piece of your code (for example on http://pastebin.com/) and give me the link.

  13. 17th June, 2009

    Ashish INDIA

    Hi,
    First Thanks for Reply,

    i had post my code

    http://pastebin.com/m13b796ac

    in that main.php contain my header and end.php contain footer

  14. 17th June, 2009

    Ginchen GERMANY

    Is it the logout that doesn’t work? Because first you named the variable $_SESSION['parent_id'] and later at the logout, you wrote $_SESSION['parents_id'] (with s!).

  15. 17th June, 2009

    Ashish INDIA

    No,
    when once i store parent id in session,when i print session on top of file at that time i am getting blank session array

  16. 17th June, 2009

    Ginchen GERMANY

    And did you put session_start(); somewhere? I think Wordpress doesn’t do that by itself, so you need to start the session yourself.

  17. 17th June, 2009

    Ashish INDIA

    No,i did not put session_start().can u tell me in which file i put session_start()?b’coz when i put it in wp_load.php file it give “header already sent” warning…

  18. 17th June, 2009

    Ginchen GERMANY

    I think it’s best to use one of the files that are included earliest by Wordpress, like index.php, wp-blog-header.php or wp-load.php. (I’m not sure why it doesn’t work in wp-load.php for you.) I would simply put it in the index.php. :)

  19. 17th June, 2009

    Ashish INDIA

    Hi,

    if i am putting session_start() in wp_load.php or index.php or in my custom script,it gives me “Header already sent” warning

  20. 17th June, 2009

    Ginchen GERMANY

    Even in the main Wordpress index.php file?!? The one where it says define('WP_USE_THEMES', true); etc.? The session_start() must be the very first line, there mustn’t be any blank spaces or anything before it. So your index.php should start with:
    <?php session_start() ...

  21. 17th June, 2009

    Ashish INDIA

    Yes.
    script that i posted is login.php in project,
    so it’s does not mean to add session_start() in index.php
    when i add session_start() in wp_load.php or login.php , then it give me that warning.

  22. 17th June, 2009

    Ginchen GERMANY

    There must be some kind of output before the session_start() then. You have to make sure that absolutely nothing is echoed before session_start(). No plain HTML either.

  23. 18th June, 2009

    Ashish INDIA

    Hi,

    i had sloved problem.

    Problem is that we are checkin and checkout files
    using vss.so i think my script is corrupted.so it have at top of script.so why it give me “header already sent” error,so at last we find it.

    Thanks for your support,

    one more think do u know how can i able to display validation error in my script like in wp-login.php

    Thanks again

  24. 18th June, 2009

    Ginchen GERMANY

    Hmm, I have never done something like that. :)
    Maybe you can simply set a variable, for example $error_msg, and then put something like this in your template:

    <?php if($error_msg) echo $error_msg; ?>
  25. 18th June, 2009

    Ashish INDIA

    ok

    Have u ever used “register plus” plugin for add extra field in user registration?

    if yes then do u use multi language functionlity in it?

  26. 18th June, 2009

    Ginchen GERMANY

    No, sorry, I don’t know that plugin.

  27. 15th July, 2009

    Ashish INDIA

    Hi Ginchen,

    I Got new Project in wordpress… i have to dispaly Product Category in front side..

    Do u have any plugin and Module for adding/editing Product Category in admin side

    please reply ASAP

  28. 15th July, 2009

    Ginchen GERMANY

    Sorry, but there are currently 5,822 Wordpress plugins, and I don’t know every single one of them. ;) Also, I don’t understand what you mean by “product category” – there are no “products” in Wordpress?!?
    The only advice I can give is: Go to http://wordpress.org/extend/plugins/ and enter a good search term. ;)

  29. 17th July, 2009

    Ashish INDIA

    Hi, i am using wp-e-commerce plugin… when we activate it,it create product page in wordpress admin.in content of that page it write like this [productspage].

    so what does this mean?

  30. 26th August, 2009

    Adrian COSTA RICA

    THANK YOU THANK YOU!

    I had the exact same problem, and you described it and solved it beautifully.

    Just a small comment — I had to place the php.ini inside the exact folder which contained the files I was executing; it’s not good enough just to place it in the root Wordpress folder as it will not affect subfolders, at least in my case.

  31. 19th September, 2009

    Priya INDIA

    Hi Ginchen,

    I ‘m having the same session unset issue while trying to add captcha to my form. I just follwed you php.ini step to solve the issue. But it did not solve my problem then i modified wp-settings.php file to add $_session variable to nounset array.

    just this, now my site is even not loading. I’m unable to access both the admin and blog sections.
    It just displays blank page, no error, nothing.

    I have replaced wp-config.php and wp-setting.php files with old files. But still problem is not resolved.

    My site is hosted on shared host.

    Please help me.

    Thanks
    Priya

  32. 19th September, 2009

    Ginchen GERMANY

    Well, if you recovered the original files, they won’t probably be the problem. Did you delete the not working php.ini? On some servers, php.ini files are not supported. Instead, you can sometimes set certain PHP options in the admin panel of your host.

  33. 23rd September, 2009

    luke UNITED KINGDOM

    Thanks Ginchen!

    I get to feel smug for Googling this first ;-) It was actually just fluke, but I’m pretty surpised there isn’t more documentation out there on this.

    Did you try using using the WP database for session stuff at all? Was thinking a script for getting and setting some custom user meta fields might work but I’ve not tried. That just ignorance on my part?

  34. 24th September, 2009

    Ginchen GERMANY

    Hmm, no, I didn’t do anything with the WP database. I just wrote a login script that used the login data from a phpBB installation on the same database. But I don’t see why your idea shouldn’t work. :)

  35. 4th November, 2009

    Rahul UNITED STATES

    You are a saviour…..
    I tried so many options…putting session_start whereever i can but couldnt get it to work consistently.
    Thanks a ton….i just updated the wp-settings.php function with a return

  36. 5th November, 2009

    Ginchen GERMANY

    Hehe, the radical method. ;) But this way, you have to edit wp-settings.php after every Wordpress update. That is why I would rather try to disable register_globals than changing the Wordpress files.

  37. 15th November, 2009

    Bernhard GERMANY

    Vielen Dank erstmal für die Infos. Hat mir schon weiter geholfen, bei meinem Problem mit Wordpress!

    Wo, ich jetzt allerdings immer noch hänge, ist eigentlich nicht dass Thema des Blogeintrags, aber du hast es in den Kommentaren erwähnt. Ich suche nach einem Login-Skript, um die phpBB3-Userdaten in meinem Wordpressblog nutzen zu können. Ich binde wie auf phpbb.de beschrieben die common.php ein, erhalte jedoch auf den Wordpressseiten dann immer die Fehlermeldung: “Fatal error: Call to a member function sql_query() on a non-object in/pages/48/f6/d0004241/home/htdocs/lupa_neu5/phpBB3/includes/cache.php on line 51”. Trotz intensiver Google-Suche habe ich noch nichts gefunden, was mir hilft. Habe jetzt angefangen über die phpBB-Cookies die Sitzung auszulesen und bin wegen eines anderen Problems auf deiner Seite gelandet.

    Um es abzukürzen, daher meine Frage: Gibt es das von dir geschriebene Login-Skript irgendwo als Plugin oder Beispiel zum runterladen?

  38. 15th November, 2009

    Ginchen GERMANY

    Also, das was ich da damals programmiert hatte, könntest Du, glaube ich, sowieso nicht brauchen. Das war für eine ganz spezielle Seite gedacht und ist damit wohl nicht wirklich wiederverwertbar. ;)

    Ich nehme an, Du willst, daß Leute sich im phpBB einloggen und dann auch gleich ins Wordpress-Backend rein können (oder umgekehrt: sich in WP einloggen und dann auch gleich im Forum eingeloggt sind)? Dafür habe ich inzwischen eine tolle Lösung gefunden: die Wordpress to phpBB3 Bridge. Allerdings geht die im Moment nur bis Wordpress-Version 2.7.1. (was ich aber eigentlich auch nicht sooo schlimm finde). Das Tolle an dieser Bridge ist, daß sie überhaupt keine große Konfiguration oder Rumgefummel benötigt – einfach wie ein Plugin installieren und fertig.

    Alternativ gibt es noch WP-United. Das habe ich vor langer Zeit mal getestet, aber da gab es anscheinend noch ein paar Bugs, durch die es bei mir überhaupt nicht funktionierte und ich es wieder gelöscht habe. Aber inzwischen hat sich da ja auch wieder was getan – vielleicht also auch nochmal einen Versuch wert.

  39. 16th November, 2009

    Bernhard GERMANY

    Hallo,

    WP-United kenne ich, ist mir allerdings bei der Weiterentwicklung immer etwas zögerlich.

    Die andere Bridge kannte ich noch nicht. Da ich aber bereits auf Wordpress 2.8.x geupdatet habe, fällt die momentan aus.

    Habe aber von dort aus weiter recherchiert und zwei weitere Bridges gefunden:

    Onepress: http://onepresscommunity.com/
    Single Sign On: http://wordpress.org/extend/plugins/phpbb-single-sign-on/

    Um es kurz zu machen: Beide laufen bei mir irgendwie nicht. Aber vielleicht helfem einem anderen User die Links weiter.

    Werde mir also jetzt doch noch WP-United anschauen und wenn das nicht funktioniert manuell eine Übergangslösung programmieren, bis eine der Bridges mit der neuesten Wordpress und phpBB-Version funktioniert.

  40. 16th January, 2010

    Simon UNITED KINGDOM

    Thanks so much for this, it saved me a lot of time integrating a music download system I wrote a while ago with a new Wordpress website/theme I have developed.

    For anyone who wants to disable Register_Globals but can’t edit their php.ini, it also possible to do it by putting this line in your .htaccess file:

    php_flag register_globals off

  41. 16th January, 2010

    Ginchen GERMANY

    You’re right, this can vary from host to host: Sometimes you have to upload a php.ini as described, sometimes you can do it in .htaccess as you just said, and sometimes there’s a checkbox in the Admin panel where you can turn off register_globals. :)

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <p> <pre lang="" line="" escaped=""> <q cite=""> <strike> <strong> | Code snippets can be posted in `backticks`. Example: `<?php echo "Hi!"; ?>`