Yii sessions stopped working after changing database server - php

My server provider moved from datacenter. While moving something went wrong and the power supply to our dedicated database server failed. They setup a new virtual database as a backup plan so we can continue to keep going. I put back a backup of the data. After this however, Yii session do not seem to work anymore. Just to specify, only the database was effected. My code was just as it is and nothing changed there.
When I try something outside of the framework like:
session_start();
$_SESSION["test"] = 100;
That still works. It will store and I can use the session variable as you would expect. However when I use Yii code like Yii::app()->session["test"] = 100. I can not recall the data.
Extra information
Cookies do work. If they did not work. I would get a pop-up every time on page reload. So certain about this.
"sessionID in cookies is changed everytime on page reload" CORRECTION: Seems the id is not change in the cookies atm.
No session files are found on the server (I believe this might be the problem?)
The session file location is writeable (tested in PHP is_writable(Yii::app()->session->savePath) returns true)
YiiSession table is being update (cleared it and it does refill again)
Main.php config contains no component for session (so everything is on default)
I tried to set some session setting including the auto create database table. I deleted the table and it was automaticly created again.
YiiSession table contains id and expire
While the expire date seem rather short, it is still set well in the future
Went from a dedicated server to a temp virtual server (Both running centOs 6.6 + MySQL).
Session are stored on a virtual server that has been unaffected by the change.
Yii::app()->getSession()->getSessionId() returns a sessionId
Any suggestion what could be wrong? It seems rather odd this problems occures after a database server change.
BIG NOTE: Just noticed that in some setting file there is a component->session. It seems we use a custom HttpSession. I guess the problem might be in there. Will look trough it (see why the previous developer decide to create a custom class for this) and then use the default options and see if that fixes it.

It seems we where using a custom class. I disabled this and just added the setting
'session' => array (
'autoStart' => true,
),
This seems to work for now. Will edit this answer if I find the specific in the custom class that caused this issue. The fact remains that this is wierd. I was not even aware of this custom class, let alone changed something in it.

Related

PHP Session Cookie Not Stored in XAMPP

For some reason the php session cookie file is not being stored on XAMPP in the default tmp directory, and I ran a search of the entire XAMPP for the session_id() and there are no results. Any ideas??
There is one file "sess_6mkb82rg31nmgjmf7i3ee7mjif" but it doesn't appear to be in the same format as a client-side cookie and is not the correct session id. The correct one is statically across multiple page loads "u8c6ldb8dcpddr55d542vodtpr". There are database queries coded into the file I found. I'm not sure what this may be. However it is in the correct directory where sessions are stored because there is a file called why.tmp and it says do not delete the session files.
What I am trying to do is find the session file and copy the contents to a new file with a new id because I've seen that creating a new id every page load is recommended on stackoverflow to reduce the risks of hacks by session fixation.
I am sure that the code doesn't change the session id after I get it from the virtual server because I am only at the point of getting the contents of the old session file so far.
I have built a successfully running framework that has no problems with sessions other than me finding the session file. It must be stored outside of the XAMPP directory or the data is saved within another file.
Thanks for your time!
There is a warning near the top of session_regenerate_id() in the php manual that states that on unstable networks, you may loose the session data. But for no apparent reason I decided to go back and look at the examples anyways and there is an example solution to this problem under the following heading in the manual:
Example #2 Avoiding lost session by session_regenerate_id()
Unfortunately this is normal for simulated services like Xampp and others users like me is currently having that problem if do you need more information Check de OficialXamppForum that talks about to create a $_COOKIE (for any propourse) after to use the method setcookie($NameCookie,$Content,time()+$Seconds); the LocalServer correctly assign the Cookie, but!, later if I going to refresh the page pressing F5, the cookie will be erased, now, I recommend you press the button (i) near the link in your browser and check if the info and expiration date are correctly like this image:
Later, if any information is correctly trust me the cookie was set correctly, that "XamppIssue" is not happen only on PHP-Cookies, also occur with the method $_SERVER['HTTP_CLIENT_IP' that is assumed to allows to read the private ip user ex: (XXX.XXX.XXX.XXX), but! in XamppServer was loaded like this "::1::" or "1" or "::1" or ":1:" or ":1" and can check this discussion here in StackOverFlow when the people says that the method was applied correctly but because is a LocalHost has those limitations at time to executing PHP .
Finally if you want to check DEFINITELY!! if your PHP runs correctly use a host like 000WebHost or Azure to discard any problems.
Have a nice day :D :D .

Codeigniter set_flashdata returns page cannot be displayed on just this one server

Ok this is a weird one. I've just moved the CodeIgniter code to my client's webhost, serverlogic.com. This code has been working on over 40 other servers, but now suddenly I'm running into walls. I'm using DB sessions.
This doesn't work:
$this->session->set_flashdata('contact_message', validation_errors());
$this->session->set_flashdata('first_name', $this->input->post('first_name'));
$this->session->set_flashdata('last_name', $this->input->post('last_name'));
$this->session->set_flashdata('email', $this->input->post('email'));
$this->session->set_flashdata('zip', $this->input->post('zip'));
$this->session->set_flashdata('phone', $this->input->post('phone'));
$this->session->set_flashdata('comments', $this->input->post('comments'));
This works:
$this->session->set_flashdata('contact_message', validation_errors());
$this->session->set_flashdata('first_name', $this->input->post('first_name'));
$this->session->set_flashdata('last_name', $this->input->post('last_name'));
$this->session->set_flashdata('email', $this->input->post('email'));
/*$this->session->set_flashdata('zip', $this->input->post('zip'));
$this->session->set_flashdata('phone', $this->input->post('phone'));
$this->session->set_flashdata('comments', $this->input->post('comments'));*/
As the set_flashdata() method uses cookies to keep track of data, could it be that there is some server limit that is hit once there is too much data stored in the cookies? When investigating the headers on my server it's setting more cookies when compared to this server.
I'm also getting a PHPSESSID cookie from their server, but I don't know where it is coming from. i'm not a server admin and as they are using Nginx I'm totally in the dark on this one.
As the set_flashdata() method uses cookies to keep track of data, could it be that there is some server limit that is hit once there is too much data stored in the cookies? When investigating the headers on my server it's setting more cookies when compared to this server.
You just answered your own question,
As you said flashdata uses cookies to store the data, the fact that it is only this one server means a possibility of two things.
This particular setup is setting more data due to your code (e.g. you might not be storing a particular variable on your other setups which just happens to be tipping this over the edge).
This server is setting more cookies by itself (a possibility with nginx), it could also be an issue with nginx doing some form of internal rewrite on your cookies so a domain issue is stopping the cookies from working properly, but this is less likely.
You said that you get a page cannot be displayed error, my suggestion, look into the server logs to find out if there are any errors. next inspect the cookies using the chrome developer tools or similar, find out if the data looks like it has suddenly been cut off.
Have you tried commenting out each set_flashdata to see if it's one particular statement? Or did you work backwards from comments? Or did you just happen to start with zip?
If you are using DB sessions the structure of your table where the session data is being stored is important. The only thing I can think of is that your columns aren't set up correctly for the types of data and the length of each amount of data being stored.
Maybe double-check the table structure with other tables you have defined on the servers.

PHP Session not written after Output(echo or print_r on external ajax Call)

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".

Intermitant Sessions

I have a site I'm deploying and I've hit a problem. I was testing my code in a sub-directory of my clients hosting package and everything seemed fine. However I've moved the folders/files to the site root and now I'm intermittently losing all session data.
I've taken a look with LiveHeaders in Firefox and these cookies are being set:
Cookie: __utma=196298984.443251570.1275554915.1275554915.1275557276.2;
__utmz=196298984.1275554915.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);
__utmb=196298984.188.10.1275557276; PHPSESSID=3f5a363de3b7ec6084c7fdf90bec78a8;
__utmc=196298984
and
Cookie: __utma=196298984.443251570.1275554915.1275554915.1275557276.2; _utmz=196298984.1275554915.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);
__utmb=196298984.189.10.1275557276; PHPSESSID=3f5a363de3b7ec6084c7fdf90bec78a8;
__utmc=196298984
I'm by no means an expert on headers so if you need other information, I should be able to get it.
For a session to work, two elements have to both be working:
First, the browser must send the same PHPSESSID cookie with every request. The session ID will change from one session to another, so if you login tomorrow (or later today, or in a different browser, et cetera) you'll get a different ID than you have now, but during a single session the ID should not be changing.
Second, the server must be able to access the same files associated with that ID during every request. By default, PHP stores that information in the /tmp/ directory. If you have access, you could even poke around there and see what's getting stored.
The first issue is easiest to test for. Take a look at what cookies are being sent while the session is working, and then check again after the session stops working and see if the PHPSESSID has changed. The most likely cause for behavior like this would be a poorly set local computer clock, poor timeout settings on the session, et cetera.
The second issue is a bit trickier. If your browser is sending the right cookie with every request, but PHP can't access the file with information about that session, the problem is with the server. You might consider storing your sessions in a database (if you're using one anyway), which is easily done with code in the PHP manual.
A couple of things that come to my mind:
1 : Make sure that if your session is being created on www.abc.com, then all browsing happens on exactly that domain, if some pages are being sent to abc.com instead of www.abc.com, this is likely to cause session/cookie problems.
2 : also make sure that session_start instruction is available on top of ALL pages.

CodeIgniter is generating multiple sessions in the database. Why?

I have a site which does a few ajax calls on page load. For some reason, CodeIgnitor is inserting 4 sessions (I'm assuming one for each ajax call) as you load the page. I'm storing the sessions in the database.
I'm pretty sure there should only be one session per browser. Firefox seems to generate only one; other browsers seem to create a whole bunch of sessions. Multiple sessions for the same user are giving me some serious authentication problems.
Why is this happening? How can I stop it?
I know the discussion took place while ago, but somebody might find this useful.
By now I've used CI session without storing its data in database. Today I decided to give it a try and immediately run across the same problem: CI was generating new session in every page load.
I checked my server time, timezone, my cookie etc. - everything I could find as a tip on forums - with no result. Then decided to debug the CI Session class myself.
Long story short, it turned out that my user_agent field in my session table was too small - VARCHAR 50 - which cuts the original user_agent string - hence CI doesn't find my session and generates onother one. I just increased the user_agent field size to 200 and everything works like a charm.
I forgot to mention that I use Mac OS X Lion.
Again, hope this will help somebody.
Check the date / time on your client OS, and on your server.
I know its too late, but maybe someone finds this page while looking for the answer...
I think it happens because CI sets an expiration time on the cookie containing the session id and if the time difference between the server and client is higher than the expiration time the cookie gets old and the server will generate a new session for the client on every request. Never took the time to figure out the exact mechanism, but happened to me several times, and this fix always worked.
I've found this topic with same problem: on every page CI generates new session. Possible solution: remove underscored from site name ( NOT "my_test_site.com", but "my-test-site.com"). At least, this helped in my situation.
Check your config.php file and make sure the cookie options are properly filled out. If they are not it cant track the user and it will gen a new session on every page load.
Check the date / time on your client OS, and on your server.
I had the same situation and confirm the solution as a fix
$config['cookie_domain'] = "example.com";
Use your domain name in this snippet.

Categories