Jump to content

How do I set cookies?


tomm098

Recommended Posts

Just wondering how I go about setting cookies from a user login. I need a username and password cookie to be set when a user logs in, and at the same time validate the username and password is correct. Can anyone tell me how to write the code?  I'm not even sure what below is right.. Thanks a lot..

 

setcookie('Username', $_POST['Username'], time()+60*60*24*365);
setcookie('Password', $_POST['Password'], time()+60*60*24*365);

 

Link to comment
https://forums.phpfreaks.com/topic/200674-how-do-i-set-cookies/
Share on other sites

setcookie('Username', $_POST['Username'], time()+60*60*24*365);

setcookie('Password', $_POST['Password'], time()+60*60*24*365);

 

 

This would work but you are storing the password in plain text - not a good idea,

 

 

at least do

 

 

$password = md5($_POST['Password']);

setcookie('Username', $_POST['Username'], time()+60*60*24*365);
setcookie('Password', password , time()+60*60*24*365);

 

 

This is still not a very secure solution but it is better than plain text[/code]

The code you have provided seems to be correct from technical point of view, but if you are going to authenticate logged in users by passing their passwords with a plain text cookie to their browsers, you are hardcore. Use sessions instead - the data you put into them do not leave the server, so nobody can acquire them while listening to the network transmissions.

 

The user data can be stored either directly in the script if this is a tiny website or in some database. In the second case you simply execute a query that checks them and returns the matched user data, if you want to authenticate.

 

The cookie you use for authentication purposes should only identify the visitor (you keep the logged in/logged out status only on the server) and it should not identify the visitor using an easy to guess or produce value, such as a username or a sequential user id number.

 

I would recommend that you generate a unique id (http://us2.php.net/manual/en/function.uniqid.php) for each user and store that in the cookie and with the user information in your user table. You would then use that unique id from the cookie to identify the visitor and match his row in the user table. If the user table says he is currently logged in, you could then set a session variable to indicate that the current visitor is logged in.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.