开发者

PHP and cookies

开发者 https://www.devze.com 2023-01-18 01:02 出处:网络
What is the best way for storing users IDs or usernames so they开发者_开发问答 will not have to login every time?

What is the best way for storing users IDs or usernames so they开发者_开发问答 will not have to login every time?

I want to forward user to the members page if the stored ID or username is compared with the one stored in database.

Is is safe to do it using cookies and how can I do that?


Don't store their username or password in a cookie. Always assume that everyone on the internet can see every cookie on a person's computer. What you should do instead is save the session_id and the IP address they accessed from to your MySQL table, then save the session_id to a cookie. Most browsers will clear session variables when you close the window, but they will not clear cookies. Therefore you first check the session (are they currently logged in), and if they're not logged in then you check the cookie (were the logged in before, and more importantly- was it from this IP address?)

Of course if they have a session_id but they're not at the proper IP address, make them log in. They could just have an ISP with dynamic IPs, or they could have been listening to network traffic and they're trying to get into the admin user without a password.


This feature should be optional to let people log in from internet-cafe and such, not leaving their data open to everyone.

Yes. a cookie is the only possible way to mark a browser.
You have to store some uniqie and unpredictable value there. Generate some hash out of user's data, store it in the database along with other user data and set it as a cookie


The safest way is to require a valid SSL certificate from the browser, and validate the user-agents certificate server sided. However, in any browser I've seen installing such certificates is a big enough pain & hurdle for users that it's probably not suited for a public website. It can however sometimes be seen in intranets.


I just wrote this solution for anyone else who is interested.

http://rabbie.id.au/my-elegant-remember-me-solution-using-php-mysql-and-cookies/


With my sites, I use a custom written Session class. This stores a sess_id and sess_hash in a cookie, which is unique for the current user. An IP address is also stored in the database, and checked against the current IP to verify it is the same computer, but that is not the main authentication mechanism. Data is then stored, serialised and base64'd in the database. I would advise against using PHP Sessions, because they can be accessed by any user with the ID. Someone posting a link to something with the PHPSESSID in it, can, for example, let them log into their account.

0

精彩评论

暂无评论...
验证码 换一张
取 消