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
https://forums.phpfreaks.com/topic/210456-is-it-safe-to-save-unpw-in-cookie/
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.

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.

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.