phpsessionsession-cookiesoverwrite

php set session_set_cookie_params based on $_SESSION is it possible?


I would like to set session timeout based on user type that is saved in the session, for example

if (isset($_SESSION['userType'])) {
    if ($_SESSION['userType'] == '0') {
        session_set_cookie_params(1000, "/");
        $page = $_SERVER['PHP_SELF'];
        $sec = "1000";
        header("Refresh: $sec; url=$page");
    } else {
        session_set_cookie_params(5000, "/");
        $page = $_SERVER['PHP_SELF'];
        $sec = "5000";
        header("Refresh: $sec; url=$page");
    }
}
session_start();

my issue is I cant access the cookie before initializing meaning session_start(); at the beginning.

so I tried putting 2 session_start() one before and one after (I was told this is supposed to give an error (it doesnt give me) but it doesn't overwrite it... and i still have the original cookie time. I tried to start the session, let it go into the if, and then destroy it, and then create it again however this didn't work for me. is it possible?

thank you:) if there are comments or im missing something or there is a better way to write a question let me know and ill try to fix it up


Solution

  • Trying to access values in the session, before you started the session, makes no sense. And neither does a second session_start call - whether it gives you an actual error or not, it will not work as desired here.

    Start the session, so that you can read the necessary values from it. Then manipulate the session cookie parameters in the desired way, and then call session_regenerate_id - that will make PHP set a new session cookie with the new session ID, and using the parameters you specified.