Search code examples
phpsessionsession-set-save-handler

Session_id behaving weirdly


So I have SessionHandler class, and my other file that put that into motion like this (cfg_session.php):

use \Classes\MySessionHandler as Sessao;

$sessao = new Sessao();

// PHP < 5.4
session_set_save_handler( 
   array($sessao, 'open'),
   array($sessao, 'close'),
   array($sessao, 'read'),
   array($sessao, 'write'),
   array($sessao, 'destroy'),
   array($sessao, 'gc')
);

register_shutdown_function('session_write_close');

session_start();

Alright, the small difference is that in my localweb I use:

session_set_save_handler($sessao) 

Because, in my localweb, it is in fact PHP > 5.5.

It works perfectly fine on my localweb, I do refresh the page, log out, log in, close tabs, open tabs, log in again and everything is normal, the PHPSESSID from my browser is equal to the one created on session's file and so on.

EDIT: I have a server with PHP < 5.4, and I'm in fact, using the code above, meant to PHP < 5.4, but it is still acting weird. Refreshes the browser, it creates another session file, but does not change the PHPSESSID. The first time I try to log in, the process goes like: It creates the session file, I redirect the user to a certain page which does another request on the server, it just creates another session file totally different from the PHPSESSID and of course, the app logs me out. That's the weird part.

But then, I try to login again normally and it logs me in, just fine. Every request, has the same ID, session_regenerate_id() works fine, everything goes OK, PHPSESSID matches the session's file created.

But then, If I logout, close that tab, open a new tab and try to log in (or just close tabs without loging out) it just does the same thing: Logs me in, create a session file, but then, it changes de session_id again and kicks me out.

I'm really stuck on this. Can't be sure if this happens because of PHP < 5.4 or anything else.

Notes: - session_regenerate_id() is being used on log in, on checking if there's session (then update time and regenerateId) and on log out.

  • cfg_session.php is required once on every page that needs to use session variables.

I need some light on this. I've already seen lots of topics, but none pretty informative or close to resolve this weird behavior. Thanks in advance.


Solution

  • Just added:

    ini_set('session.use_cookies', 1);
    

    The thing is: I wasn't using it on my localweb, but I read that the default is 1 (true) and probably, on my live server, it was set to 0. Now it works normally. Thanks.