Sessions and cookies
I currently have a website that allows my visitors to login via a simple script i've pasted together and 开发者_开发百科wrote. Currently I only use sessions to keep visitors logged in. Are there any advantages to adding cookies to my website to store user logged in status?
Or is there a better way altogether?
using PHP
If you are using PHP sessions then you are using cookies. PHP stores session ID in cookies and the session data to a file on the disk on your web server.
@Ramiro Gonzalez Maciel he said he has made that script, he doesn't need frameworks to take as examples. Frameworks usually have scripts wrapped up and well placed.
To respond that question:
I usually store in cookie some md5 strings that are combined from his md5(password) and his username so I'll know next tim he enters my website that is was logged in so I wouldn't make him login again
my example:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// sql and escape stuff witch will return 1 if he has entered a valid login
if($sqlreturn == 1){
// do login
$wraplogin = md5($username."-".md5($password)."-".SECRET_KEY); // I always define a define('SECRET_KEY', 'mysecretkey'); in global file.
// now you can store that $wraplogin in cookies and remember his login. Next time he enters the website, you read that cookie, compare it with what you have in your database and let him in.
}
?>
Now I know that is not the best example, but I've personally used it in very large websites (>500.000 users) and none has hacked in yet :)
That's the advantage in cookies for the login part.
Best of luck.
The web frameworks ( Java Servlets and others ) usually use cookies to identify sessions; the other usual option is URL parameters. So assuming you're using any web framework, it's probably already using cookies to store the session id. The Web Framework will use this ID to identify the Session object in every request. Although cookies survive server restarts, since they're stored in the browser, Session objects usually don't unless you've configured Session persistence.
If you want to users to "auto login" as in the usual "rembember me" option many web sites implement, you would have to persist Session objects if your framework provides that. Or implement a similar system, using cookies to store a "logged in token", and checking that token when the user access the system to auto-log them or send them to a login page. ( Edit: like Mihai proposes in other answer )
If you want to implement your own method, I suggest checking how the popular web frameworks implement this, specially the security and privacy aspects of storing user data in cookies.
精彩评论