WordPress

Session-Variablen in WordPress

Drei Tage lang wäre ich fast verzweifelt, als ich eine WordPress-Seite um ein selbstgeschriebenes Login-Script erweitern wollte. Lokal funktionierte alles einwandfrei, doch sobald ich es hochgeladen hatte, schienen die Session-Variablen nicht mehr übernommen zu werden: nach dem Login war man jeweils einen Klick lang eingeloggt und danach sofort wieder ausgeloggt.

Nach etlichen erfolglosen Google-Suchen (im Nachhinein googelt es sich ganz leicht danach, aber versucht mal was dazu zu finden, nachdem Ihr nicht weiter als bis hierher gelesen habt) fand ich endlich die Ursache, nämlich die Funktion wp_unregister_GLOBALS() in der Datei wp-settings.php. Hier ist sie:

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

Was macht diese Funktion?

  • Zeile 27/28:
    Wenn auf dem Webserver die PHP-Einstellung register_globals nicht aktiviert ist, dann macht sie überhaupt nichts (daher auch die unterschiedlichen Verhaltensweisen meines Scripts auf meinem lokalen und dem Live-Server). Ist register_globals jedoch aktiv, geht es folgendermaßen weiter:
    • Zeile 34:
      Wie der Kommentar schon sagt, werden hier alle globalen Variablen aufgelistet, die nicht resettet werden sollen. Wie man sieht, ist $_SESSION nicht dabei!
    • Zeile 36–41:
      Nun werden nacheinander alle globalen Variablen durchgegangen und gelöscht.

Kurz gesagt: Wenn register_globals aktiviert ist, wird $_SESSION bei jedem Seitenaufruf gelöscht. Kein Wunder also, daß man nicht mehr an seine Session-Variablen rankommt!

Wozu das Ganze?

Nun ja, zum einen geht WordPress davon aus, daß es sich komplett um jeden Bereich der Seite kümmern soll – schließlich ist es ja eine Art von Content-Management-System. Und das beinhaltet eben auch, daß es die Verwaltung sämtlicher Variablen übernimmt.

Was aber noch viel wichtiger ist, ist die Tatsache, daß die Verwendung von register_globals längst veraltet ist und das Feature mit PHP 6 sogar komplett entfernt wird. Von der Programmierung mit solchen Variablen wird inzwischen überall abgeraten, da sie Sicherheitsrisiken birgt. WordPress versucht also offensichtlich, das Verhalten von deaktiviertem register_globals nachzuahmen, um die Sicherheit zu erhöhen und eventuelle Variablenkonflikte zu vermeiden.

Abhilfe

Nachdem ich erst einmal hinter dieses Rätsel gekommen war, lag die Lösung natürlich auf der Hand: Ich muß register_globals auf dem Webserver deaktivieren, damit WordPress diese bescheuerte Funktion gar nicht erst auszuführen braucht. Dazu lädt man einfach in sein WordPress-Verzeichnis eine Textdatei namens php.ini hoch, in der die folgende Zeile steht:

register_globals Off

Weitere Informationen zum Thema gibt es auf php.net:

Hinterlasse einen Kommentar Arrow

  1. 12. Dezember 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. 21. Januar 2009

    Satranc TURKEY

    I think we must find a solution without register globals.

    Thanks.

  3. 21. Januar 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. 22. Januar 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. 22. Januar 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. 5. April 2009

    Caner TURKEY

    Hallo Ginchen,

    Danke für die Info. ;)

    Du hast mir das Leben gerettet. :D

    Grüsse aus Antalya
    Caner

  7. 12. Mai 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. 26. Mai 2009

    KRL SPAIN

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

  9. 17. Juni 2009

    Kristina CANADA

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

  10. 17. Juni 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. 17. Juni 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. 17. Juni 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. 17. Juni 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. 17. Juni 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. 17. Juni 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. 17. Juni 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. 17. Juni 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. 17. Juni 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. 17. Juni 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. 17. Juni 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. 17. Juni 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. 17. Juni 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. 18. Juni 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. 18. Juni 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. 18. Juni 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. 18. Juni 2009

    Ginchen GERMANY

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

  27. 15. Juli 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. 15. Juli 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. 17. Juli 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. 26. 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. 19. 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. 19. 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. 23. 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. 24. 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. 4. 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. 5. 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. 15. 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. 15. 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. 16. 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. 16. Januar 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. 16. Januar 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. :)

  42. 7. April 2010

    Ivan Novak UNITED STATES

    Hey there, I found your site racking my brain trying to find a good solution. While I did try the solution you propose, it did not work for me.

    I did a bit more searching and came across this blog post:
    http://www.frank-verhoeven.com/using-session-in-wordpress/

    The solution he provides works perfectly, allows the use of $_SESSION within your wordpress site, and is upgrade compatible.

    Thanks, –Ivan

  43. 7. April 2010

    Ginchen GERMANY

    Oh – well, yes, I thought it was somewhat self-evident that you have to put session_start() somewhere before you can start working with sessions. :) My solution was especially for those cases when session_start() has already been added to a WP file like wp-config.php, and it still doesn’t work.

    But you are right, I should have mentioned that. Thanks for the link, it’s a good guide.

  44. 24. Juli 2010

    Max NEW ZEALAND

    Hi all! I am developing a theme for commercial use and require sessions to run to add some functionality that is needed.
    At the moment wp_unregister_GLOBALS() seem to be a great problem for me, since modifying wp-setting.php manually is not an option. Has anyone got any ideas on how to add SESSIONS global variable to a $noUnset list, by coding only inside my theme folder? Or maybe desable wp_unregister_GLOBALS()? Or perhaps deactivate register_globals in php setting file of the server? But remember I am limited to doing that by code only from inside my theme folder. Any advise on this will be much appreciated, I’ve been trying to find a solution for a week now and getting very frastrated at wordpress…
    Cheers
    Max

  45. 24. Juli 2010

    Ginchen GERMANY

    The cleanest and most logical solution is, as I wrote, to disable register_globals. You could try to add a php.ini with register_globals Off to your theme folder, but it’s not granted that it will work from there, and certainly not on every server, because the way PHP ini values are set vary a lot depending on the host. (Some use a php.ini file, others only allow these settings to be changed from an admin panel, etc.)

    Another idea I have right now is: Perhaps you could override wp_unregister_GLOBALS() in your functions.php using override_function(). Just replace it with an empty function. Actually, that’s a pretty neat idea I just had there! Tell me how it worked out. ;)

  46. 24. Juli 2010

    Max NEW ZEALAND

    Thanks so much for your help =)) Interesting tho the register_globals is set to off in my godaddy server configuration, but it is php version 5.2.5, not the 5.3 that I have on my local host. The sessions work flowlessly on the local host with php5.3, but they don’t work at all on the web‑ the sessions start, but die with page refresh, so even a simple counter wouldn’t work.
    The override_function made my blog die by a horrible deph, but I am researching into the metter now‑ simse that wordpress does have similar things that let you override they core functions‑ remove_action and remove_filter functions. I will let you know if I find a solution. Thanks very much again for taking your time to help =))

  47. 25. Juli 2010

    Max NEW ZEALAND

    I’ve commented out the call to wp_unregister_GLOBALS()- in the online version it didn’t have a body to it in wp-settings, just a call for it. And guess what‑ nothing happend as I suspekted, since register_globals were off in both of my server configurations. I register sessions function in functions.php, have add_action(‘init‘, ‚f_name‘) and do a session start inside the body. On my local server it worked anyway I did it‑ even with session start in the top of the header… But as soon as I upload code online‑ sessions die horribly. I think I am at give up stage, I’ve searched alto for a week, tryed everething. Time to move on and try and achieve the same with cookies, just set it to not display anything if the cookies are off. And do some checks perhaps to see if the cookie code has been modified….

  48. 25. Juli 2010

    Ginchen GERMANY

    That sounds really strange. Have you tried to put session_start() into to a very early-loading file? For example, I like to put it at the very bottom of my wp-config.php, and I’ve never had any problems with that.

  49. 10. August 2010

    TJ Meier UNITED STATES

    I’m in the same boat as Max who commented on 25 July 2010. I have session_start() at the top of wp_config. I tried the php.ini in the same directory as wp_settings. I then did surgery on the wp_unregister_globals function in wp_settings with some//’s and it seemed to work for a while, but then returned to some strange behavior once again.

    For example, my $_SESSION['test'] was unset in php script unrelated to WordPress, but the pages on WordPress still register the value of $_SESSION['test']–and even seem to insert some values of its own. All other non-Wordpress scripts show nothing for the variable during all this.

    If I figure out a solution for this I’ll leave another comment heh.

  50. 16. August 2010

    John UNITED STATES

    I Love you man.

Erlaubtes 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> | Codeschnipsel können in `backticks` gepostet werden. Beispiel: `<?php echo "Hi!"; ?>`