Aug
2008
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-Einstellungregister_globalsnicht aktiviert ist, dann macht sie überhaupt nichts (daher auch die unterschiedlichen Verhaltensweisen meines Scripts auf meinem lokalen und dem Live-Server). Istregister_globalsjedoch 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$_SESSIONnicht dabei! - Zeile 36–41:
Nun werden nacheinander alle globalen Variablen durchgegangen und gelöscht.
- Zeile 34:
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:
- Welche Bedeutung hat die PHP-Direktive register_globals für mich?
- Verwendung von Register Globals
- Superglobals
ubergoober
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.
Satranc
I think we must find a solution without register globals.
Thanks.
Ginchen
Well, if you really want to make it work with
register_globalson (which you shouldn’t, because it’s unsafe and allows for code injections!), you could simply edit line 34 and add$_SESSIONto it, so it looks like this:After that, session variables should not be unset anymore.
Satranc
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.
Ginchen
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.
Caner
Hallo Ginchen,
Danke für die Info.
Du hast mir das Leben gerettet.
Grüsse aus Antalya
Caner
tkm
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.
KRL
Im was debuging for hours before find this, thanks a lot, you rock!
Kristina
or you add _SESSION in the noUnset array of that function….
Ginchen
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.
Ashish
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
Ginchen
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.
Ashish
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
Ginchen
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!).Ashish
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
Ginchen
And did you put
session_start();somewhere? I think WordPress doesn’t do that by itself, so you need to start the session yourself.Ashish
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…
Ginchen
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.
Ashish
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
Ginchen
Even in the main WordPress index.php file?!? The one where it says
define('WP_USE_THEMES', true);etc.? Thesession_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() ...Ashish
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.
Ginchen
There must be some kind of output before the
session_start()then. You have to make sure that absolutely nothing is echoed beforesession_start(). No plain HTML either.Ashish
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
Ginchen
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:Ashish
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?
Ginchen
No, sorry, I don’t know that plugin.
Ashish
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
Ginchen
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.
Ashish
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?
Adrian
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.
Priya
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
Ginchen
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.
luke
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?
Ginchen
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.
Rahul
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
Ginchen
Hehe, the radical method.
But this way, you have to edit
wp-settings.phpafter every WordPress update. That is why I would rather try to disableregister_globalsthan changing the WordPress files.Bernhard
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?
Ginchen
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.
Bernhard
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.
Simon
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
Ginchen
You’re right, this can vary from host to host: Sometimes you have to upload a
php.inias described, sometimes you can do it in.htaccessas you just said, and sometimes there’s a checkbox in the Admin panel where you can turn offregister_globals.Ivan Novak
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
Ginchen
Oh – well, yes, I thought it was somewhat self-evident that you have to put
My solution was especially for those cases when
session_start()somewhere before you can start working with sessions.session_start()has already been added to a WP file likewp-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.
Max
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
Ginchen
The cleanest and most logical solution is, as I wrote, to disable register_globals. You could try to add a
php.iniwithregister_globals Offto 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 aphp.inifile, 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.Max
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 =))
Max
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….
Ginchen
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 mywp-config.php, and I’ve never had any problems with that.TJ Meier
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.
John
I Love you man.