?
Solved

How to setup encryption with a Remember Me Cookie

Posted on 2005-03-15
22
Medium Priority
?
254 Views
Last Modified: 2010-04-06
Hi,

I have a "remember me" cookie working but I would like to know how to encrypt it's contents??

This is the code I am currently using :-

if (isset($_POST['remember_user'])) {
 $cookiedata = $_POST['username']."|".$_POST['password'];
 setcookie("autologin", $cookiedata, time() + 31536000);
}



<?php

// Check if cookie is set
if (isset($_COOKIE['autologin']) && !isset($_SESSION['username'])) {

 // Get the cookie and split the username , password from the cookie.
 $splitcookie = explode("|",$_COOKIE['autologin']);
 $cookie_user = $splitcookie[0];
 $cookie_pass = $splitcookie[1];

 // Run the query to check for the user.
 $query = "SELECT * FROM users WHERE user='$cookie_user' AND password='$cookie_pass' LIMIT 1;";
 $logincookie = mysql_query($query) or die(mysql_error());
 
 // If no user found for the cookie data, display error or exit from the loop.
 if (mysql_num_rows($logincookie) < 1) {
  echo "Cookie Error - Auto Login Failed!<br>\n";
 }
 else {
  // User found for the cookie data, login the user and set it in SESSION variable.
  $users = mysql_result($logincookie, 0, "username");
  $_SESSION['username'] = $username;
 }
}
?>

Thanks
Jon

0
Comment
Question by:jalexan123
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 7
  • 5
22 Comments
 
LVL 32

Accepted Solution

by:
Batalf earned 1000 total points
ID: 13543387
You shouldn't store the password in the cookie. What you should do is to let the cookie be a unique string and have an own database table with reference to this string and to the user.

example:

table:

LOGIN
---------------------
ID int
uniqueID varchar(255);
userID int

then create the cookie to be something like

$cookieValue = uniqid();
setCookie("autologin",$cookieValue);

Then create a new record in the table login after successful login with username and password:

insert into login(uniqueID,userID)values('$cookieValue','$userID');

0
 

Author Comment

by:jalexan123
ID: 13543405
Thanks,

I got the script from the question below which seems to use this to encrypt the password :-

$cookiedata = $_POST['username']."|".md5($_POST['password']);

http://www.experts-exchange.com/Web/Web_Languages/PHP/Q_21086125.html

Or am I going down the wrong path, like I said it is all fully working so I would like to keep the script if possible but just encrypt the password.

Thanks
Jon
0
 
LVL 32

Expert Comment

by:Batalf
ID: 13543413
OK, you could probably use that.

Then change the query

$query = "SELECT * FROM users WHERE user='$cookie_user' AND password='$cookie_pass' LIMIT 1;";

to

$query = "SELECT * FROM users WHERE user='$cookie_user' AND password='".md5($cookie_pass)."' LIMIT 1;";
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543419
I guess you meant encrypting the cookie stored in the local computer. If yes, you can use crypt function ( http://www.php.net/crypt ) to encrypt the cookie password.
0
 

Author Comment

by:jalexan123
ID: 13543426
Ok, so when the cookie is encrypted I guess it can still be read from the site they are returning to??

Sorry about the dumbness of that statement, I am just trying to work out how, if the cookie is encrypted on the users machine that it can be read again by the site they are returning to?

Thanks
Jon
0
 
LVL 32

Expert Comment

by:Batalf
ID: 13543433
You can't decrypt it but you could compare encrypted cookie against encrypted value in the datbase.

with mdb5:

$query = "SELECT * FROM users WHERE user='$cookie_user' AND password='".md5($cookie_pass)."' LIMIT 1;";

with crypt:

$query = "SELECT * FROM users WHERE user='$cookie_user' AND password='".crypt($cookie_pass)."' LIMIT 1;";

0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543464
if (isset($_POST['remember_user'])) {
 $password = crypt($_POST['password']);
 $cookiedata = $_POST['username']."|".$password;
 setcookie("autologin", $cookiedata, time() + 31536000);
}

and the script as :

...
...
// Get the cookie and split the username , password from the cookie.
 $splitcookie = explode("|",$_COOKIE['autologin']);
 $cookie_user = $splitcookie[0];
 $cookie_pass = $splitcookie[1];

// Run the query to check for the user.
$query = "SELECT * FROM users WHERE user='$cookie_user' AND password='$cookie_pass' LIMIT 1";
....
....

Since the password stored in the cookie is already encrypted, you dont need to check it again in the query.

Make sure while inserting a new record, password is encrypted using crypt() function.
0
 
LVL 32

Expert Comment

by:Batalf
ID: 13543493
Of course. I was thinking wrong.

But for this to work, the password has to be encrypted in the database too. If you want to have it in plain text as well, maybe a encrypted version too, so that you could check it like this:

$query = "SELECT * FROM users WHERE user='$cookie_user' AND encrypted_password='$cookie_pass' LIMIT 1";
0
 

Author Comment

by:jalexan123
ID: 13543532
Hi ldbkutty,

When you say

Make sure while inserting a new record, password is encrypted using crypt() function.

Do you mean just for the script you mention. Do I need to do it when a user is signing up to my site for instance?

Thanks
Jon
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543540
>> Do I need to do it when a user is signing up to my site for instance?

Yes !
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543566
The concept is: "autologin" Cookie holds the password stored in the database. (both of them are encrypted)
0
 

Author Comment

by:jalexan123
ID: 13543585
Hi,

Ok, on my user sign up form it is this action :-

<?php if ( isset( $errorText ) ) echo $_POST['password']; ?>

and in the php code at the top of the page :-

$insertSQL = sprintf("INSERT INTO users (address, payacc, name, email, `user`, password) VALUES (%s, %s, %s, %s, %s, %s)",
                         GetSQLValueString($_POST['address'], "text"),
                             GetSQLValueString($_POST['payacc'], "text"),
                                   GetSQLValueString($_POST['name'], "text"),
                         GetSQLValueString($_POST['email'], "text"),
                         GetSQLValueString($_POST['user'], "text"),
                         GetSQLValueString($_POST['password'], "text"));

Just wondering where I insert the crypt and do I need to decrypt it later on when someone types there password to sign on?

Really sorry for the newbie question.

Thanks
Jon
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543599
$insertSQL = sprintf("INSERT INTO users (address, payacc, name, email, `user`, password) VALUES (%s, %s, %s, %s, %s, %s)",
                         GetSQLValueString($_POST['address'], "text"),
                           GetSQLValueString($_POST['payacc'], "text"),
                              GetSQLValueString($_POST['name'], "text"),
                         GetSQLValueString($_POST['email'], "text"),
                         GetSQLValueString($_POST['user'], "text"),
                         crypt(GetSQLValueString($_POST['password'], "text")));
0
 
LVL 32

Expert Comment

by:Batalf
ID: 13543610
To insert users:

$insertSQL = sprintf("INSERT INTO users (address, payacc, name, email, `user`, password) VALUES (%s, %s, %s, %s, %s, %s)",
                         GetSQLValueString($_POST['address'], "text"),
                           GetSQLValueString($_POST['payacc'], "text"),
                              GetSQLValueString($_POST['name'], "text"),
                         GetSQLValueString($_POST['email'], "text"),
                         GetSQLValueString(crypt($_POST['user']), "text"),
                         GetSQLValueString($_POST['password'], "text"));

And when someone logs in crypt the password where you check for match

$sql = "select ID from users where username='".$_POST['username']."' and password='".crypt($_POST['password']."'";

But as mentioned, you could also add an extra column to your users table in order to have both a plain version and an encrypted version of the password.


0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543653
Suppose a user registers and enters his password as "abc".

Let us assume crypt("abc") is equal to "SFSdfster32325fdh"

** The value "SFSdfster32325fdh" is stored in the database and in the cookie. **

When the user comes back to your site and types "abc" in the password field, the query:

$query = "SELECT * FROM users WHERE user='" . $_POST["username"] ."' AND password='" . crypt($_POST["password"]) . "' LIMIT 1";

will check for the record that has password as "SFSdfster32325fdh".
0
 

Author Comment

by:jalexan123
ID: 13543677
Ah-ha, that makes sense, cool I will try all that out and get back to you.

Thanks
Jon
0
 

Author Comment

by:jalexan123
ID: 13544286
Hi,

Ok, I can encrypt the password but and I know I am slight OT here, I having nothing like you show for $query, this is the closest I get :-

if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $password=$_POST['password'];
  $MM_fldUserAuthorization = "";
  $MM_redirecttoReferrer = false;
  mysql_select_db($database_dbCON, $dbCON);
 
  $LoginRS__query=sprintf("SELECT confirmed, id, user, password FROM users WHERE user='%s' AND password='%s'",
    get_magic_quotes_gpc() ? $loginUsername : addslashes($loginUsername), get_magic_quotes_gpc() ? $password : addslashes($password));

Thanks
Jon
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13544309
I dont get you :(
0
 
LVL 32

Assisted Solution

by:ldbkutty
ldbkutty earned 1000 total points
ID: 13544335
You shoule have crypt() function in the $_POST["password"]. Like this :

if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $password=crypt($_POST['password']);
  $MM_fldUserAuthorization = "";
  $MM_redirecttoReferrer = false;
  mysql_select_db($database_dbCON, $dbCON);
 
  $LoginRS__query=sprintf("SELECT confirmed, id, user, password FROM users WHERE user='%s' AND password='%s'",
    get_magic_quotes_gpc() ? $loginUsername : mysql_real_escape_string($loginUsername), get_magic_quotes_gpc() ? $password : mysql_real_escape_string($password));
}

// mysql_real_escape_string() is better than addslashes() function.
0
 

Author Comment

by:jalexan123
ID: 13687870
Hi Guys,

I would like to thank you for your help, unfortunately I am too inexperienced with php to get this to work. Nothing to do with the answers but I am a complete newb at this, ie I am still stuggling with chapter 1 of Php for Dummies!!

So I think the best recourse is to give half the points to ldbkutty and the other half to batlaf.

Thanks for your help once again, it has been really appreciated.

Thanks
Jon
0

Featured Post

WordPress Tutorial 1: Installation & Setup

WordPress is a very popular option for running your web site and can be used to get your content online quickly for the world to see. This guide will walk you through installing the WordPress server software and the initial setup process.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It's sometimes a bit tricky to use date functions in Oracle BPEL. I'll explain quickly how you can add N days to the current date. In a BPEL process this can be useful, and you can adapt it to fit your needs. First of all, let's see how to add 1 …
JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question