Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keep user logged in when he visit the same page again?

currently im using session to log in the user. but when i close the browser and open it again i have to log in again. how do you keeo the user logged in in lets say 2 weeks.

is it through cookies then?

like image 992
never_had_a_name Avatar asked Dec 09 '09 22:12

never_had_a_name


2 Answers

So you want a "Remember me on this computer" option? Here's a language-agnostic way how you can do it:

  1. Create a DB table with at least cookie_id and user_id columns. If necessary also add a cookie_ttl and ip_lock. The column names speaks for itself I guess.
  2. On first-time login (if necessary only with the "Remember me" option checked), generate a long, unique, hard-to-guess key which represents the cookie_id and store this in the DB along with the user_id. Also store this as cookie value of a cookie with a before specified cookie name. E.g. remember. Give the cookie a long lifetime, e.g. one year.
  3. On every request, check if the user is logged in. If not, then check the cookie value cookie_id associated with the cookie name remember. If it is there and it is valid according the DB, then automagically login the user associated with the user_id and postpone the cookie age again.

As to the security risks, if the key is long and mixed enough (at least 30 mixed chars), then the chances on brute-forcing the login are negligible. Further on you probably already understood what the optional column ip_lock is to be used for. It should represent the IP address of the user. You could eventually add an extra checkbox "Lock login to this IP (only if you have a static IP)" so that the server can use the user's IP address as an extra validation.

And what if one hijacked the cookie value from an user without an IP lock? Well, there's not much to do against this. Live with it. The "remember me" thing is funny for under each forums and account-hijacks wouldn't hurt that much there, but I would certainly not use it for admin panels and that kind of webpages which controls the server-side stuff.

It's after all fairly straight forward. Good luck.

like image 122
BalusC Avatar answered Sep 27 '22 22:09

BalusC


Read this: http://www.php.net/manual/en/session.configuration.php

The setting that you need is session.cookie_lifetime. Session cookies (eg ones that do not have a lifetime) are deleted when the browser is closed. If you want the sessions to stay alive for longer, set that setting in php.ini, httpd.conf, or .htaccess. Possibly even with ini_set

Edit: Actually you can use this function:

session_set_cookie_params (86400*30);
session_start()

86400*30 is 30 days.

See here: http://www.php.net/manual/en/function.session-set-cookie-params.php

like image 25
gahooa Avatar answered Sep 27 '22 20:09

gahooa