What is the correct and safe/secure way to keep a user logged in? cookies? session? PHP && MYSQL

前端 未结 5 1845
刺人心
刺人心 2020-12-12 18:29

Later I was asking how to logout correctly a user, now I seeing that using only cookies to keep a user logged in is not secure at all.

Keep the password in a cookie

5条回答
  •  心在旅途
    2020-12-12 18:58

    I would use a session.

    To help a little on security, once a users credentials have been verified use session_regenerate_id - since the session id is what is passed across in a cookie this is important if someone is sniffing around while login in processed.

    DO NOT STORE any information in the session pertaining to access credentials - a userId is often sufficient; personally I build a user object which I store in the session (these get auto serialized/unserialized between request - but you can read on that independantly).

    IF you wish to set a cookie so the user doesn't have to login on the next visit perhaps store the userId and an autogenerated token which can be checked against in the database (or similar) - I would add extras to the checking too - like storing the last ipaddress with the token to check as well, if they don't match then ask for login once more.

    There are quite a few approaches that can be taken - I don't offer all/'the best' - get your code reviewed by people in a php community - you learn more that way.

提交回复
热议问题