Jump to content

Is it safe to save un/pw in cookie?


eevan79

Recommended Posts

I am using this script for "remember me" option:

                      if (isset($_POST['rememberme']))
                        {
                          /* Set cookie to last 1 year */
                          setcookie('username', $_POST['user_name'], time() + 60 * 60 * 24 * 365);
                          setcookie('password', sha1($_POST['user_pass']), time() + 60 * 60 * 24 * 365);
                        }

 

Is it safe to save user data in cookie or there is better way? Can somebody steal password if there is more than one user at same computer? What do you suggest?

Link to comment
Share on other sites

um...why would you do it that way? sorry for the question sounding rude. I don't mean it to, it's just that you should never store personal data in a cookie.

 

I would recommend you look at sessions, or generated hashes that you store in a cookie and a database.

Link to comment
Share on other sites

The way I do it is I store a generated hash in the cookie which I store in my database. The validation code goes like this:

 

if(!isset($_SESSION["myusername"]) || $_SESSION["myusername"] == ''){
if(isset($_COOKIE["dtb_auth"])) {
	$sql = "SELECT DTB_Users.Username FROM DTB_Users WHERE DTB_Users.Session = '".$_COOKIE["dtb_auth"]."' limit 1";
	$result = mysql_query($sql);
	if(mysql_num_rows($result) != 0) {
		$Username = mysql_result($result,0);
		$_SESSION["myusername"] = $Username;
	}
	else {
		setcookie("dtb_auth", "", time()-3600, "/");
		header("location:index.php");
	}
}
else {
	header("location:index.php");
}
}

 

At the login page I have this code:

 

if(!isset($_COOKIE["dtb_auth"]) && $_POST['remember'] == 1) {
	/* expire in 20 years */
	setcookie("dtb_auth", session_id(), time()+631138519, "/");
	$sql="UPDATE DTB_Users SET Session = '".session_id()."' WHERE Username='".$myusername."'";
	$result=mysql_query($sql);
}

 

Pretty straightforward I think. If the normal session elapsed, check for 'perpetual' cookie, in this case dtb_auth (my 'rememberme' cookie). It checks it against the database and if it checks out, assigns a new session to it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.