Avatar of burnedfaceless
burnedfaceless
 asked on

Using cookies to remember a login

I would like to use cookies to remember a login.

I know how to use sessions but not cookies.

Do you use both at the same time?

If you want to post a brief example I would really dig that.
PHP

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
burnedfaceless

ASKER
That was excellent - I have one more question - if I want the user to stay logged in for a year

Then I multiply time() * 60 * 60 * 24 * 365 correct?


Thanks - Google was giving me some really bad old examples from early PHP 5
burnedfaceless

ASKER
Awesome man disregard my last question
Julian Hansen

You are welcome.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Julian Hansen

Just as an addendum to my answer - to properly determine user login state it is a good idea to validate the session token - in other words checking for existence alone is not good enough so,
// CHECK IF COOKIE EXISTS AND GET IT IF IT DOES
$session_key = isset($_COOKIE[SESSION_NAME]) ? $_COOKIE[SESSION_NAME] : false;

// NO VALID KEY - NOT LOGGED IN - BOUNCE TO LOGIN PAGE
// SPECIFICALLY CHECK THAT THE SESSION KEY IS VALID
// DONT JUST CHECK FOR EXISTENCE
if (!isSessionValid($session_key)) {
   header('location: login.html');
}

// IF YOU GET HERE - USER SESSION IS VALID
// OPTIONALLY RESET THE TIMEOUT ON THE SESSION
set_cookie(SESSION_NAME, $session_key, time() + 3600, '/');

// NOTE: NO BROWSER OUTPUT TO HAPPEN BEFORE HERE

Open in new window

isSessionValid is a custom function that would be specific to your user authentication scheme.