Link to home
Start Free TrialLog in
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.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of burnedfaceless
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
Awesome man disregard my last question
You are welcome.
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.