I have an application with multiple regions and various incoming links. The premise, well it worked before, is that in the app_controller, I break out these incoming links and set them in the session.
So I have a huge beforeFilter() in my app_controller which catches these and sets two variables in the session. Viewing.region and Search.engine, no problem.
The problem arises that the session does not seem to be persistant across page requests. So for example, going to /reviews/write (userReviews/add) should have a session available which was set when the user arrived at the site. Although it seems to have vanished!
It would appear that unless $this->params is caught explicitly in the app_controller and a session variable written, it does not exist on other pages.
So far I have tried, swapping between storing session in 'cake' and 'php' both seem to exhibit the same behaviour. I use 'php' as a default. My Session.timeout is '120', Session.checkAgent is False and Security.level is 'low'. All of which should give enough leniency to the framework to allow sessions the most room to live!
I'm a bit stumped as to why the session seems to be either recreated or blanked when a new page is being requested. I have commented out the requestAction() calls to make sure that isn't confusing the session request object also, which doesn't seem to make a difference.
Any help would be great, as I don't have to have to recode the site to pass all the various variables via parameters in the url, as that would suck, and it's worked before, thus switching on $this->Session->read('Viewing.region') in all my code!
Try setting the security setting in your /app/config/core.php file to medium or low. That solved a session problem I had.
i had the solution or at least that work for me
you try to pass from controller reviews action write to controller userReviews action add right???
check that your controller userReviews must end whit php tag "?>" and NO MORE SPACE
SO if you have someting like this
line
999 //more code lines
1000 ?>
1001
your session fail
you have to had this
line
999 //more code lines
1000 ?>
sorry for my bad english
soo you
It would appear that unless
$this->params is caught explicitly in
the app_controller and a session
variable written, it does not exist on
other pages.
That sounds like the proper behavior unless you are posting data from page to page. If you want any variable to persist, it should either be set in the model (where it will persist with the association), or passed on in a function, or set in the session explicitly using the session component:
$this->Session->write('Viewing.region');
(see: http://book.cakephp.org/view/398/Methods)
On a related note, I've had most success with sessions stored in the database. Run the file from app/config and set it to db. See if that helps.
Also, do the Cake core tests for the session work?
Might it be this problem? Essentially, cake's session resets if the user-agent changes
It's a shame that I ran into this very problem you mention a few days ago and now I cannot find the link that helped me solve it.
Also: are you using database or plain php sessions?
I'm going to go out on a limb here without being able to look at your code, but might it be possible that your "reviews" controller (or whatever) has its own beforeFilter() and doesn't call its parent's beforeFilter() explicitly?
This has burned me before...
I got some issues like this. Session set using some controller was not available in another , controller . I could clear the issue after spending few hours . There was a white space afer the end of php tag at the bottom . After clearing the line and white space after the last ?>
tag worked fine .
I had this problem when moving a CakePHP site. My problem was that the session directory wasn't writeable. You should make sure the folder app/tmp and all it's subfolders (including sessions) have permission 777.
Related
I have a PHP application custom_appli in /var/www/httpdocs.
Wordpress is installed on the same server in /var/www/httpdocs/new_cms/wordpress.
I need to retrieve user->ID using SESSION of custom_appli.
I have tried to insert :
require( './new_cms/wp-snapshots/wp-blog-header.php' );
global $user;
$user = wp_get_current_user();
echo "ID :".$user->ID;
writing wp-load instead of wp-blog-header doesn't change anything no matter whether I use include or require_once.
Could you please give me a link or advice on how to obtain user from SESSION?
Thanks in advance
Details and info are sparse, but here's how I would do it (I know about 5 methods, these are the least painful):
As mentioned, wp_get_current_user() gets you close, but that is generally only usable on the page for the user as in "on load" only. So from the WP served page you can get user ID (and all other info) and the session and have something that is usable. There are many ways to use that data to solve your problem, not really smooth all the time. Session data is etherial, beware.
Another way to go about it is to use wp-load.php and wrap it in middleware. this script bootstraps WP and allows queries and similar in the "bootstrapped" wordpress environment providing the applications internal API. I would consider adding wp-load to custom_appli "in the right way" and use that as middleware between the 2 applications. You will still need to identify the user as in many cases.
Without more information it is hard to guide you, but I can tell by your needs and the code already in the post that you are setting up for possible problems with dependencies, possible name-spacing collisions($user is something that could bite you as a global), and a myriad of other ways to loose time. If custom_appli needs a user ID, send it the user from WP on page load or similar.
When/why do you need that info? What is the flow?
You can also traverse a lot via session ID info too (depending on configuration).
FWIW I have passed user information successfully from 2 freestanding applications on different servers, it was very hard to do correctly, but it is possible.
Update after clarification
As mentioned "wordpress-user and cusstom-appli have same users" is possibly a replication of functionality, specifically running 2 tables(?) or logic. Just some feedback.
Basically you are wanting to hook the "logged in" status of a WP user. I see no mention of:
FK/relationships built on user (easy but a little more work)
ACL/permission based access on custom appl
No serializing of data or similar to the WP user (user in general)
Any of the above might have me change the solution. Here is a pretty clean prototype I wrote for you that is about 15 lines of code.
It follows some code from wp and essentially:
Makes sure PHP session is initialized via the theme functions.php
Uses the WP login (authentication) success to add a var to the session
On logout unsets the var (!IMPORTANT!)
Also makes sure the session is set when not logged in or the key is not present
Is easy to pick up outside of WP via session (custom_appl.php)
I tested this and it worked fine locally on one of my installs, I don't see any reason why it would give you problems. I would harden this a little more, but this is only a prototype showing how to use the key tools in PHP and WP.
wp_get_current_user() is a function in wp-includes/pluggable.php, which is loaded by wp-settings.php. I'm not sure how exactly WordPress bootstraps itself but I'd try to include wp-settings.php if anything.
I'm using a CMS-framework that initates session_start() upon page creation, however 90% of the site visitors are guests without the need for sessions, resulting in an awful lot of empty session-variables at server.
What's the best practice here? IF logged in, I need to know at an early level so I guess it means is both:
Postpone session_start() until it's actually needed
Keep the session_start() at an early stage, but make it conditional based on existance of cookie PHPSESS
Or is there a better fix, unknown to I?
Many large sites postpone the session initialization until it's actually needed, e.g. on cart pages and the user profile screen of each user.
In theory this isn't that complicated, if you were using a config file which would be required within all pages you could simply swap out a different config file for the pages that don't require any user recognition.
You're using a CMS-framework so perhaps you're somewhat limited within it. If you can differentiate the page creation process, using session_start(); in one case and not in the other, then this shouldn't be that big of a deal. Keeping the logged in users logged on once returned to the other area of the system (the index file etc) would not work though. Of course you could be using local_storage to aid you with that but relying on JavaScript only isn't very reliable.
The easiest way would probably be to spit the system into two areas, one which doesn't use any sessions (index, other information files, etc) so the process behind those page creations would be different, i.e. not using sessions.
Perhaps you could have a session class like mentioned but it would most likely conflict with other previously outputs causing the sessions to fail, but if you could flush the other output then this could possibly work, but it's kind of a hack in my opinion and it wouldn't really solve the previously mentioned problem.
Have you considered changing the lifetime of the sessions? The default setting is 24 minutes but would reducing it to 15 change anything? Is 24 minutes really that big of a deal for you? Maybe the settings in your environment make them be even longer. Are there other aspects of the system that might be the actual performance issue? Are you hosting the system yourself or do those empty sessions really not matter?
If you're expecting a lot of guest traffic without the need for sessions, then don't use it unless you absolutely need it. What I typically do is create a class for session, and add the session_start to the constructor of the class. Then, when I need sessions, I can simply call the session class within an underlying global.class.
I have a problem with Smarty 3.1.13.
Smarty kills my session. Every time I refresh my page, $_SESSION array is empty.
When I comment line $smarty->display('index.tpl'), everything is OK.
Any ideas?
You have to start your session before $smarty->display('index.tpl')
This is beacause the session cookie needs to be send in the HTTP header and therefore session_start will need to be called before the first line of output.
So make sure session_start() is placed before $smarty->display('index.tpl')
I can't post this time code, because it's divided to many parts (framework), and I don't have permissions to publish them.
Thanks for your time, but I found another problem with Smarty and solusion for my problem:
When you write templates in extending way (one template extends other), you can't see Smarty debug window, even if $smaty->debug=true
When your running template is extending another, and $smarty->debug = true, it kills your session. Don't ask me why, I didn't have time to check it. I think it's a bug.
I´m having some serious trouble debugging this particular problem and I hope someone has a clue what i´m doing wrong.
I have a Custom CMS system working that uses Paragraphs as building blocks that get updated using Ajax(prototypejs) calls and functions that parse the HTML chunks in given order, clean them up and save this data in associative arrays in a Session variable.
Users log in, Session is created and I can check for this session without problem in every page I need it. The system works directly on the definitive websites, so the user can see his updates on realtime and browse the site as a normal user would do, but editing.
So, nothing new here. But here is the weird thing.
Enduser site on edit mode(admin user logged in): path "/"
After the logged status is verified, a function processes the editable content and saves an associative array to session, it also starts some javascript objects for editing every paragraph. Data is actually saved, I can use an external script to check if it´s there after this php script ends.If I load a new page(new content), Session gets updated with new data)
Admin User modifies a paragraph using an Inplaceeditor and this HTML chunk is send via Ajax to a php script that starts the named session, reads the present session data, checks if a paragraph should be modified, appended or deleted and reassigns values to existing array keys in $_SESSION. if i make a var_dump() o print_r to $_SESSION after assigning new data is there.After that the script echoes the processed html, and ajax updates the original paragraph on the calling page.
This script is in /admin/cms/...etc, that means at least 4 directories inside the root of the site.
When the script ends, I check using the same session dump script to see if data was really written/commited, but no, $_SESSION has only the original data from the calling page.
Same ID, same session name, same session_start() but no data gets written.
This whole operation is very quick, so I though it could be a speed problem, scripts ends before session_write_close can make his work.
But if I add a new key to $_SESSION array and put some data there, data gets updated and written. If i don´t output anything on this script and just process data and set session variables it also get´s updated and written.
It´s like some members of $_SESSION array are getting blocked to update.
What i did to track this error and what i´m sure i´m not doing wrong.
1.- register_globals are off of course
2.- session_name() and session_start() are always present and in the given
order. I used to have multiple
session_start() -close on a same page
to use several named sessions, but to
refine the problem this is not longer
so.
3.- I use session_write_close() after session data is processed. Also
tried without, letting php decide
when to commit data, but no luck.
4.- I`m using only cookies for SID.
5.- sessions are stored on /tmp, i can see the data getting updated.
I also tried using a custom save
handler on DB, but same problem,
"_write" got only called when no output as present.
I searched php.net, stackoverflow, google, etc for this subject. I never ask without investigation, this is my first time in many years...but it´s just so unlogical it must be something tiny a haven´t thought of.
The most weird thing is that when I just process data without output $_SESSION gets updated ok. But if i modify this script afterwards by adding the output and try again, instead of just having the new(last) value present I get the original value back, the one created by the calling page at first place, sometimes after playing around a few times! PHP can´t cache values between scripts or?I dont have globlals on.
I´m really clueless. This system worked flawless on PHP4.3, since i´m using 5.3.3 for two moths my users where caliming data where getting mixed up, so i checked and yes, there are serious problems. Today I updated to (5.3.6) and I can´t get this session values commited.
Script code called via Ajax:
<?
session_cache_limiter('nocache');
session_name("CMS_ses");
session_start();
include('../htmLawed/htmLawed.php');
include("utils_cms.php");
include("../../../php/utils_array.php");
$value=$_POST['value'];
$editorId=$_POST['editorId'];
$clase=$_POST['clase'];
$editorId=str_replace("pre","",$editorId);
$value=html_entity_decode(stripslashes($value),ENT_QUOTES);
if (strlen(trim($value))==0)
{
die();
}
$value="<div id=\"$editorId\" class=\"$clase\">$value</div>";
$newXHTML=$value;
$retorno=CMS_nuevoBloque($newXHTML,$editorId);
$_SESSION['data']['CMSeditores']=$retorno[1];
$_SESSION['data']['CMScont']=$retorno[2];
session_write_close();
print_r($retorno[0]); //Offending part...without everything works
?>
really nothing strange here....main page code is even simpler, no strange php directives, etc.
Here is the header of the caller page
include 'php/db.php';
$len=$_GET['len'];
$sec=$_GET['sec'];
$cont=$_GET['cont'];
$admfin=$_GET['admfin'];
$fecha=$_GET['fecha'];
$token=$_GET['token'];
$cur=$_GET['cur'];
$PHP_SELF=$_SERVER['PHP_SELF'];
session_cache_limiter('nocache');
session_name("CMS_ses");
session_start();
$passvar='';
unset($adm);
if ((!empty($_SESSION['cms_logged'])) and (!isset($admfin)) )
{
$nivelpermisos=$_SESSION['cms_logged_group'];
$useractual=$_SESSION['cms_logged'];
$adm=1;
}
elseif (empty($_SESSION['cms_logged']))
{
unset($useractual);
}
//.........rest of the code
UPDATE: I did late night tests and found someting i don´t understand.HElP please:
It has not only to do with Sessions but also with Mysql Querys. Same code, but instead of trying to write to $_SESSION array i made a simple update to a Innodb table using the session_id. When i Output some code, the update does get executed,(i can output the query string and no mysql_error() or notice) problems, but checking the database the row doesn´t get updated. Letting the output out if the script and Query does get commited. Only common thing is sessions are started and output is made.
I restarted Apache, etc(who knows) but no luck. Then i made something really stupid, because this is a server side thing. I changed my browser to Firefox(using safari) and everything works! Ok, recheck, back to safari, nothing works. Both running side by side, same issue. PHP is server side, how can different browsers handle code different, can a browser say to apache rollback, request not handled or call the same script twice without notice(checked safaris developer console and the script is called only once) ? Can safari resubmit data silently because it "thinks" ajax failed? I checked headers using firebug and Safaris developer tools , nothing strange but whenever i make a Ajax call with safari, the caller page reloads data(Aka conection to server...).
I really don´t understand nothing.
I had a similar problem to this (if I have understood correctly). I needed to force session data to be written (for a custom session driver) after scripts have finished running. A shutdown function can be registered which should run after scripts have finished.
Maybe this will solve (or help you to solve) your problem.
http://php.net/manual/en/function.register-shutdown-function.php
Thank's for your help. I was doing everything in the right order and still session data was not being written. Session names where necesary because sometimes we test many sites on the same domain using the same custom CMS. So, finally, after making lots of test and no luck, i found that register globals was active on this server(we never use it, code was written having this option off in mind of course), but it messes with sessions!. Switching this off made a huge change. No more problemas. I also made a custom session handler in DB, so i could track the problems in an more centralized way.
Conclussion: Never use register globals + named sessions, an complex data in sessions.
Anyway, i will give this issue more time and more tests. Ajax calls are also sometimes too fast, i had to put a sleep command so writing the session data was really done.Thanks
I am not sure but few suggestion i think may be helpful.
delete session cookies before refreshing the page for testing purposes :)
Ensure that you're not assigning any arrays with a key containing the pipe character (|). This will prevent the session data from being serialized and saved.
Do session_regenerate_id(true); many cases session_write_close doesn't seem to matter with out session_regenerate_id. or just do session_start() after session_write_close() if you are relying on SID ; and in your case i think this is what is causing problem to you as you are ending the current session every time and not re starting it for the next page. hope u get my point. Further more To Make sure data is actually flushed out to the browser use ob_end_flush();
i could not understand the connection between
$_SESSION['data']['CMSeditores']=$retorno[1];
$_SESSION['data']['CMScont']=$retorno[2];
and
$nivelpermisos=$_SESSION['cms_logged_group'];
$useractual=$_SESSION['cms_logged'];
i think you need to paste some more code where the data part is causing problem instead of admin login part.
i hope this helps you.:)
Is there any reason you're establishing the session name twice? I've had issues in the past where I would establish the session without a name, then another piece of script (not mine) was naming the session. Even at the end of the script I was able to print out the session variable, but once I went to a new page my session had been forgotten. It wasn't until I copied the name included in the 2nd script into my session call that it was solved.
Check that there's no other session names being used; also, maybe try only naming the session once, at the first call to the session?
Question: Are you calling session_start() first thing... before ANY output to the browser and before any variables are assigned?
Sounds silly but give it a try.
Also, why are you using session names? Really not necessary unless you have a lot of session variables with the same name serving different purposes and if thats the case then you need to fix that first!
I had a similar problem but it was having with ie few years back. IE manipulates the header on its own way and that causes strange php bugs that you can find in php.net archives.
#Diego Pino Navarro, please see this help page and find Safari and it's issues with php.
I also found "Safari "forget" http-authentication's logon-information".
I am writing an TYPO3 Extension and everything is working fine right now. I Access the GET Variables via
t3lib_div::_GET('rid');
This does work on the testsite I added my Extension to, but if I add it on another subsite of the same page which is in an access-restricted area this does not work. I use var_dump to look at the GET vars, and on the normal site it works, on the restricted I dont get anything (not even NULL!) Just no output and the logic also does not take it. How do i fix that, or ist there another way to access the GET variables in that case?
I guess that happens because within the first request the output of your extensions is stored within the cache. And the second output is just generated out of the cache (instead of regeneration within your extension). To avoid that you could just make your Extensions not cacheable (USER_INT) or use cHash to show that cache-entries are related to more input values than just the simple page-url...
cHash is explained in the the mysteries of cHash article and I guess you'll find enough information regarding USER vs. USER_INT Objects with google ;)
I have no clue why, but seems to be some kind of caching issue. I always cleared the Typo3 cache so it was not directly a problem with that, but if i set the "nocache" flag for the site the plugin is on, everything works fine. So actually it has nothing to do with the access thing, but I do not understand why this doesnt work without nocache.