Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice for using Cookies for authentication with PHP?

I'm looking for tips and ideas on how to best incorporate authentication with PHP using Cookies.

Should each php script check for the cookie value to determine if the user is still logged in? Should there be one script that does this check and Include that script from each of the other scripts? Can the cookie value be seen by php from different depths of the filesystem?

Like: blahblahblah.com/ and blahblahblah.com/login/

Can they both read the cookie?

Lots of questions on one post, but thanks!

like image 538
Dan Whitinger Avatar asked Oct 27 '09 23:10

Dan Whitinger


1 Answers

nothing is safe on the client side.

You change the login flag on Cookies easily on any browser. Thus it is more recommended to be saving login-related data on php's $_SESSION

If you wish to extend the session, simply look at session_set_cookie_params().

By default, the same session will be used for the current domain and all the paths on that domain. Thus it is readable for both blahblahblah.com/ and blahblahblah.com/login/

When the user logs in, save the username and the hash of the password in the Session.

At the start of each script, verify the Session's username and password with the one in database. If is correct, then set a flag (e.g. $userLoggedIn = true) to indicate on server-side that the user is logged in. else false.

like image 155
mauris Avatar answered Oct 05 '22 22:10

mauris