phpsessionsession-cookiesini

Purpose of checking session.use_only_cookies when creating a session?


I am currently creating a session where I check the ini file to see if use_only_cookies is set. Is this really necessary? I mean, is there a way for the client to mess with the ini file? The reason why I am asking is because if the user is redirected to the same domain, this check would just loop over and over again.

How can I prevent this when the session is global? or is this even necessary to add when creating a session?

$session_life   = 3600;
$session_name   = 'SecUser';
$http_only      = true;
if(ini_set('session.use_only_cookies',1) === false){
   header('500 Internal Server Error', true, 500);
   exit();
}
$cookieParams = session_get_cookie_params();
session_set_cookie_params($session_life, $cookieParams['path'], $cookieParams['domain'], $secure, $http_only);
session_name($session_name);
session_start();
session_regenerate_id(false);

Solution

  • In my opinion it's not necessary.

    And no, the client can't mess with the ini file. That's for sure.

    If you just want a standard session with a session id, you can do it the quick and easy way: Just use session_start() - and that's it! No ini_set(), no session_get_cookie_params(), no session_set_cookie_params(), no session_name(), no session_regenerate_id(). All those functions are only required for special cases.

    In some environments (e.g. shared hosting) you don't have access to php.ini. That's why PHP lets you get and/or set some of those settings from whithin the app. Besides, there might be some (very exotic) use cases where somebody would want to change this ini setting dynamically...

    See here: http://php.net/manual/session.configuration.php#ini.session.use-only-cookies
    They clearly recommend to have this set to true. The purpose of this very setting is: Before cookies where (a) invented and/or (b) popular, PHP had a fallback mechanism for users who couldn't (or refused to) accept cookies. In this case the session id was somehow appended to every (!) URL. Very few use this today, since today almost everybody accepts cookies (at least session cookies), since every website uses them ;-)

    Now for your question: No, this wouldn't crash anything. Actually, for 99.99% of all users it wouldn't make a difference! The setting just deactivates the fallback from cookie to URL.
    The absolute worst case is that a non-cookie enabled user is not going to get the session.

    Somewhat offtopic: Checking for failures this way doesn't make sense to me anyway: If you try to catch a problem you should either inform the user about what they could do now or (even better) try to process it in another way. Just throwing a 500 error and exiting doesn't make much of a difference since this is what PHP does anyway when it crashes...