I am new to PHP and am currently struggling with the following:
I have a login page where I start a session as below which works well so far.
session_start();
// ...
$_SESSION["Customer"]["username"] = $username;
$_SESSION["Customer"]["email"] = $email;
Now I have never used sessions before but assume they die once a user closes their browser and I would like to keep them logged in so that they don't have to do this whenever they re-enter the page. My thought was to use a cookie for that but I am not sure how I can store my session in a cookie.
I did some research on this and came across the following but I am not sure if that's the right approach and how to use it for what I need.
Can someone help me with this ?
session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] );
lifetime
in my case would be indefinite so as long as possible,path
would probably just be "/",secure
would be true
and I wouldn't need the httponly
.
Many thanks in advance, Mike
In fact, php does store the session in a cookie - a single cookie, usually called PHPSESSID
. This corresponds to a file (the filename of which is the value of the PHPSESSID
cookie) on the server which is a set of key/value pairs, such as those you outline above.
Provided that the user has cookies enabled, sessions will work fine. The main thing to make sure is that every response uses session_start()
; otherwise you won't be able to access values within $_SESSION
.
If you want this session cookie to stick around after the browser closes, you need to use session_set_cookie_params()
(documentation here) which you would call before session_start()
.
I'd definitely recommend against the approach of 'eternal' sessions, just from a scalability point of view - bearing in mind each session corresponds to a file on the server these could build up after a while (especially if you are a high traffic website).
There is one approach which involves storing a separate cookie on the user's browser, containing login information which your website can look for within $_COOKIE
, enabling an 'auto-login' process, which you could explore. I'm not sure it's the most secure approach though.
Hope that helps a little.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With