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:

Einen Kommentar hinterlassen 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. :)

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!"; ?>`