Session handling in PHP and Zend - php

I got a really strange problem in my PHP webapp.
If I log in, everything works fine for the duration of my session.
If I come in the next day, my webapp returns me to the Login page (as I expect).
The problem is that once I log in, parts of my site work and parts don't. The parts that don't return strange error messages and then I'm logged out and need to log back in. The strange thing is that some days some parts don't work and other days other parts don't work. If I delete all cookie values I can see, that doesn't solve the problem. The problem is only solved by deleting the entire cookie itself and then logging in again.
I've turned off garbage collection (because on Ubuntu there is supposedly a cron job which does it automatically even though I can't see it) but the issue was occurring before that.
So in terms of simplicity my intention is two-fold:
- To add code to my Login page to delete the cookie entirely (assuming I can do that from PHP)
- To move session storage from my webserver to my MySQL DB (because I'm in my dev environment but preparing to build my test environment which will be a cluster of webservers, not just one)
My questions are:
- Is there any way to ensure session values die reliably and gracefully rather than lingering and wreaking havoc?
- Is it possible to delete an entire cookie from PHP code, rather than just cookie values?
Many thanks.

After being a constant problem for a while, this issue has gone away. I've actually determined the cause and so I thought I'd post a quick update. Basically I had three sites I was accessing on my domain, my own webapp, a CMS Admin page and another admin tool. I've determined that the session cookies between my webapp and CMS admin were interfering with each other. If I use different browsers to access the different sites, the problem doesn't reoccur. It was driving me up the wall. Thanks to those who posted suggestions/responses. I appreciate it. I'll mark this as closed.

Related

session_regenerate_id(): Session object destruction failed, when running site via security scanners?

Is this normal, as I have tried two different scanners and they both seem to produce the same errors, so I'm assuming maybe it has to do with the way scanners work - as I don't get these errors when viewing the site normally (the site also functions fine - as expected).
Ofcourse, I could just ignore it and clear the error log (when I've finished scanning my site), but I'm just curious and would like to know why (and if there is a 'fix')?
FYI:
When the site is being scanned; I get the same error repeatedly (on pages where session_regenerate_id(true) is included).
The scanners which I have tried are both free Firefox Add-ons; 'SQL Inject Me' (by Security Compass) and Websecurify.
I'm running these tests on my site (via 'localhost').
The sessions are file based.
The issue is with your code and the way you handle sessions.
You are running a scanner that is going through your website and trying to manipulate various inputs and than analyzing the responses to see if the attack succeeded.
When you have session_regenerate_id(true) on a page, that method call tries to delete the current session and start a new one.
The reason that this happens on the scanner is because the scanner is probably taking some paths through the applications that a typical user wouldn't take. So if the scanner hits a URL that executes PHP code that has session_regenerate_id(true) inside of it and there isn't a current session, than you will receive that error.
Ideally you should have a check before calling session_regenerate_id(true) to see if a current session exists. If it doesn't than you should take the user to the login page and ask them to re-authenticate.
Please let me know if you have any questions.
Ofcourse, I could just ignore it and clear the error log (when I've finished scanning my site), but I'm just curious and would like to know why (and if there is a 'fix')?
Upgrade your PHP version to the current stable one: PHP 5.4.7.
Run the security checks again. If the error still happens (which I highly doubt), this needs further inspection. In that case (and even earlier) you should have added your session configuration (it is larger than you might think) to the question.
Also the code which is triggering this is unknown. The function session_regenerate_id() is normally used in the context of the session management.
Because the concept of session is not that easy to grasp many developers (incl. me) do errors in that field more often. Some useful debugging functions:
session_status
headers_list
Try using session_write_close(); before session_regenerate_id(true).
A possible reason for the problem is that your code is creating parallel queries. I had the same trouble and this helped me.

PHP session resets when switching through tabs on the same domain

I have a website (www.mysite.com) with a private backend (www.mysite.com/admin)
When I'm adding content to the site in the admin area and switch back and forth between tabs in the same browser window to see the content I'm editing, my session is getting expired/ended/terminated and I'm redirected to the login page again.
I have used the same code many-many times before on many web sites (this is a CMS I've made by myself) without a problem. The only thing I can think of is that this particular website is hosted on a different web server and maybe it's a matter of a php.ini setting or server configuration. Any ideas?
Have you checked your browser cookies? (the actual client-side ones?) or tried your luck with another browser? It may sound a bit strange, but I had a similar problem and in my case it had to do with these cookies. It may be worth figuring out because of your odd problem. As you might know the phpsession value is stored in that cookie and so is the domain.
Good luck!
This could be a result of several things, but my first instinct is to check and see if the session cookies are expiring very quickly. Sometimes server headers may change expiry values. You may also want to check the cache headers being sent by the server. If you are using asynchronous functionality on the admin area, it is possible that somehow the server is changing the expiry of cached files which could affect this.
I am eager to see the solution to this.
A few things to check:
session.cookie_lifetime setting - Possibly too short; 0 is the default and keeps the cookie until the browser closes
session.cookie_path setting - You'll want this to be '/'
Session storage - Make sure the session data is being written.
Explicitly call session_close() if your sessions are stored in a database. That will ensure they are written before your objects and database resources are destroyed.
If serving through any sort of proxy, check for any changed header information.
If caching, check your dynamic pages (requiring sessions) are being served by your web app and not the cache.
If testing with your local /etc/hosts, first clear your cookies so the new server's cookies are fresh and don't conflict.
Confirm in your browser that the cookie is in fact being stored. Maybe it's not actually coming back in the header.
I had a problem like this before. I was just uploaded a site from my localhost to a remote host, and I haven't change the nameservers yet. The hosting company provided me with a temporary url to be able to see my website. The problem was that this url was like this https://server_name.grserver.gr:8443/sitepreview/http/my_site.gr/, the result was that any browser didn't accepted the session cookie because I didn't had an SSL sertificate so the sessions didn't worked at all. I browsed a little the plesk panel and I found an other temporary url that was using http protocol, with this everything was ok. So if you are using https try to check if you have a problem with your ssl sertificate (for expample if it has expired). You said the problem occurs when you login in the admin page, do you switch then to https?
There could be several reasons. As there is no code or no details about the site provided , I am assuming that the problem might be if you are using htpasswd. If u are using htaccess authentication, then your session gets destroyed.
From experience, I can tell you a few things.
First, sessions need to be started with
session_start();
At the top of every page you want to use sessions.
Next, to save session data, you need to call another function to tell php that you are saving stored data. That function is
Session_write_close();
That function is needed on the bottom of the page when you are finished writing data to a session and want it saved for later use.
With those two combined, that should allow you to properly write to a session, save the data you entered into it, and access it later on your site.
Good luck.
The problem has been found after reading this topic.
I had a custom php.ini in the root dir and apparently it was interfering with the $_SESSION. I don't know why but after deleting it everything works fine.
At first it seemed as if the problem was opening pages located in different sub-folders in several browser tabs however it narrows down to a sub-folders issue and the fact that the $_SESSION wasn't accessible across them.
I'd like to thank everyone that put some time into trying to help me figure this out.

Joomla Session Automatically Logs Out, No Content

I am running a Joomla 1.6 site, which I recently moved to a new server. I moved the site file system using rsync, and I replicated the MySQL database using MySQL utilities. The previous server has running Ubuntu server 10.10 and the new one is Ubuntu Server 11.10. Everything seems to be working correctly, except one thing...
In the site configuration, a user's session is set to expire after 24 hours. On the previous site it had been working correctly. On this new site, I have found that after a user logs in successfully and uses the site for some time, the user is logged out intermittently (randomly?), well before 24 hours, and then upon logging back in to the site (even in the back-end) the site is completely blank. The main menu is not there and there is no content. The logout button still appears, however, and the main banner. If the user logs out and then logs back in, usually all the content appears again like it should, and the site continues to function properly until the next time the session is booted.
Does anybody have any experience with this? Is there a place a can start debugging to find out why the session is ended abruptly? Why can I log in to the site and still not see any content?
I share the same issue. Being logged out, then logging back in and seeing nothing.
It is very random, and will happen 10 times in a row, or never for two weeks.
This happens on a site that's quite complex (plenty of extensions), and has some traffic (5000 hits/day + 100 admin access / day) on J. 1.7
There is obviously something wrong with the session management.
In an attempt to make the site faster we have tweaked the database and moved the session table to memory, and I believe this may be the key aspect here.
Once we had repeated errors happening and clearing the sessions table solved it (until the next day), so I would guess it's connected to the in-memory sessions table.
If your table is in memory, try moving it to disk; if it's not, try emptying it and see if it happens again, and post back! Good luck
More news.
After long debugging the issue was related by an exception in the core which was not properly handled (related to saving an item with a duplicate alias, i.e. saving a second article in the same category with the same title/alias).
For us it was enough to migrate to J 2.5.3 to solve the issue.
Anyway, as a general comment, such behaviour could be related to an error in some Joomla files, which should leave traces in your error_log (else enable error logging).
It took my customer 3 months to understand what they were doing and describe it so finding an error might speed up the diagnostics.

PHP 5.3.3 - running session_start() in subdirectory kills existing session

I've been trying to track down some annoying session issues since my webhost upgrade to PHP 5.3.3 awhile back. I've determined that if there is an active session, calling session_start() from a subdirectory kills the existing session. As an example, I start a session and a user logs in to domain.com/index.php then the user navigates to domain.com/members/ which fires start_session() ... the user's session is lost.
I've dug around for this and can't find anything similar. Is there a PHP configuration that would account for this behavior?
Calling session_start() multiple times with that version of PHP shouldn't cause any problems, however there are other possible causes.
One possible explanation is that the client's browser isn't sending the session id back to the server. You can test this out by comparing the session id that both pages produce. Assuming that you have a controlled environment where you can test this properly, you can use session_id() to get the session.
It might also be that the user is hitting a different webserver. Since (by default) PHP stores sessions to disk, there is no way for multiple servers to share the session information. If this is a shared host, it's probably quite unlikely this is the cause. You can test this out however by using phpinfo(). It should give you enough information to determine if it's the same server or not. For multi-server systems, I'd look at storing sessions in memcache or mysql.
if your sessions works all right within the same directory (it is unclear from your question), there is the only possible reason for such a behavior, a pretty obvious one: "directory" cookie parameter.
It seems it is set to somewhat unusual value, other than default "/" for the session cookie parameter.
You have to check it out.
Anyway, it is almost useless to try ANY session/cookie related problem without an HTTP interchange log.
You have to use some HTTP sniffer, like LiveHTTPHeaders Firefox addon to see what cookie header was sent by the server and which one was returned by client.
Otherwise it's all going to be shooting in the dark.
Okay, as it seems from your yonder comment, the session id remains the same, so, no HTTP issue can be a reason. The issue become a kinda tricky to spot.
Could you please post your test script here?
I've spent quite a long time searching, trying, testing for what looked like the same problem. As google kept sending me here, I think sharing the solution might help others (though I feel strange posting on a 2011 question):
Session variables set in /bar.php were not set in /foo/foobar.php.
It realised that the issue had nothing to do with folder/subfolder when I finally found out that the link in http://www.example.com/bar.php was pointing to http://example.com/foo/foobar.php (missing www).
Correcting the URL in the html link solved the problem. Having no time to dig deeper, what I can figure out is that (in my config) Apache makes no difference and serves pages indifferently with and without www, whereas PHP doesn't share the session between what it considers being two different domains, example.com and www.example.com.
Is there a PHP configuration that would account for this behavior?
Yes, if the storage for the session data differs between those calls, the $_SESSION content will differ as well. The storage can be configured, see http://php.net/manual/en/session.configuration.php for all configuration options you have with sessions.
Next to that if PHP is unable to read the session store, you will get an empty array as well.
I can't tell you if this is the issue with your problem, but probably it's helpful.
BTW, calling session_start() and than having an empty $_SESSION is commonly a sign that a new session has been created. You can verify this if you use cookies for your sessions and you output headers_listDocs:
echo '<pre>', var_dump(headers_list());
If it contains a new cookie for the session, the session has been created with this request.
Lots of good suggestions here. Thanks everyone. I spent a good chunk of the weekend digging into this and wasn't able to directly resolve it. I ended up demonstrating to my webhost that this problem happens on two of his hosted sites and doesn't happen in a default install of PHP. To work around the problem, I ended up moving all of my login and session logic into a single class.
Wanted to share another answer, found in this SO: Session variables not accessible in subdirectory answered by clayRay.
My answer was that I had a custom "php.ini" file saved in the root directory, and moving those directives into ini_set() calls solved it. You could also shove those over to .htaccess if your host allows.

session_start() Hangs The Server

Totally confused by this one...
We have a WAMPServer installation set up, running a number of virtual hosts from various document roots.
Just recently, one particular domain has started hanging the server. We traced it down to session_start(). If we comment it out, there are no problems (except, of course, for the fact that we can't do anything with the session). With it uncommented, it will hang the page load and, with enough reloads, will hang the entire server.
All of the other sites still work perfectly with their sessions. As far as I know, there is nothing different with the way sessions are being worked with. I am looking further into it (in case someone changed something) but right now I'm hoping for some direction :)
So, any thoughts?
So, I'm guessing that it's an application layer problem because the other sites' sessions are working properly. However, this assumes that they have their sessions configured the same way - save yourself some time by double checking that your site isn't doing some "unique" in its configuration compared to the other sites.
I would next examine the other session related code that is running in your application. It could be that by calling session_start() you're putting your application into a state where it will run other code. For example, maybe there's a block of code that says "only run this function if this session variable is set" and by starting the session you're exposing that variable, where it wouldn't have been exposed and therefore not run the offending function if the session wasn't started.
Good luck.
My first guess would be file permissions if you are using file based sessions. If you are using database sessions, then I would check to make sure a table isn't corrupt. Also, is it Apache, PHP or something else that's locked up?
It's possible that you hit a bug in your underlying infrastructure that you won't be able to resolve. You should at least clear all existing sessions before moving forward with trying to diagnose this.

Categories