?
Solved

Creating A "Remeber Me" Cookie?

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

I have a login page where a user uses their username and password to login. However if they come back to the site later on they have to enter those details again.

Does anyonw know how I can get a "Remeber Me" function working? I am just starting out in the world of php so I am not sure where to start. I am using a MySQL database.

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
  • 13
  • 11
24 Comments
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13542493
0
 

Author Comment

by:jalexan123
ID: 13542517
Hi,

Many thanks ldbkutty, I had read that one before. I was a bit confused(yeah, it's not that easy!) as my passwords are not encrypted in the database. So I wasn't sure which bits I needed to edit :(

Thanks
Jon
0
 
LVL 32

Accepted Solution

by:
ldbkutty earned 2000 total points
ID: 13542549
no, its very easy. Diablo's code/explanation doesn't deal with password encryption at all.

For example consider the username and password as "jalexan123" and "mypassword" respectively. If the "Remember Me" form checkbox field name is "remember_user" :

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

will set a cookie named "autologin" that stores the username and password as "jalexan123|mypassword" (note: either you should not allow anyone to have username with | or you can change | to anything you wish).

<?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 tablename WHERE username='$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.
  $username = mysql_result($logincookie, 0, "username");
  $_SESSION['username'] = $username;
 }
}
?>
0
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 

Author Comment

by:jalexan123
ID: 13542785
Hi,

Thanks for the help!!  

Will get onto it right away!!

Cheers
Jon
0
 

Author Comment

by:jalexan123
ID: 13542936
Hi Again,

Do I need to set up any fields in the MySQL database? I have inserted and tried to use the remember me button, everything was going well until I get this error :-

Table 'db2d3d.tablename' doesn't exist

Thanks
Jon
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13542954
You have to give the actual table name in which you store the username, password.

In this line :

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

Replace the "tablename" with your original table name and fields "username" , "password" with user name, password table columns. Similarly in this line :

 $username = mysql_result($logincookie, 0, "username");

you have to repace "username" with the user name column of your table.
0
 

Author Comment

by:jalexan123
ID: 13542977
Doh! Sorry for my stupidity, thanks, will make the changes now!

Thanks
Jon
0
 

Author Comment

by:jalexan123
ID: 13543051
Hi,

Well, it seems to be working, I say seems because I can't tell. How do you test whether a cookie is working? The thing is the session always kept you logged in for 30 minutes anyway unless you logged out, I don't really want to sit here for the next 2 hours trying my cookies! Is there anyway to test it is working?

Thanks
Jon
0
 

Author Comment

by:jalexan123
ID: 13543063
And saying that, I can see the cookie when I view cookies in Firefox, is it easy to encrypt the cookie password or is that going to be just too much?

Thanks
Jon
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543064
print_r($_COOKIE); will list all the existing cookies. Or simply try this :

<?php
print_r($_COOKIE);
if(isset($_COOKIE["username"])) {
 echo "Username cookie is set : " . $_COOKIE["username"];
}
else {
 echo "Username cookie not set!";
}
?>
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543076
It depends on the encryption alogorithm you use. MD5 is a good one way encryptng hashing algorithm. Encrypt the password with MD5 and store it in the database (and ofcourse in the cookie).
0
 

Author Comment

by:jalexan123
ID: 13543113
Thanks, this is the message I get :-

Array ( [autologin] => jonj161|mypassword [PHPSESSID] => e903135cdcfd7e5bd6ae917191b8a9dc ) Username cookie not set!

Hmm, must have made a wrong turn :(

It is strange because this is what firefox is saying :-

Name      autologin
Value      jonj161%7Cmypassword
Host      localhost
Path      /mysite/
Expires      15 March 2006 10:31:10

?
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543188
Oops, sorry the cookie name is "autologin", not username. Cookie works in your case as you can see it in the array. However you can do this if you want :

<?php

if(isset($_COOKIE["autologin"])) {
 echo "Autologin cookie is set : " . $_COOKIE["autologin"];
}
else {
 echo "Autologin cookie not set!";
}
?>
0
 

Author Comment

by:jalexan123
ID: 13543248
Hi,

Ok, message now says

Autologin cookie is set : jonj161|mypassword

So I assume that is OK? and working?

Ok, I am going to accept your excellent answers ldbkutty, and I am willing to start a new question if needed, but is there anywhere that can tell me how to do the encryption and limit cookie times, I want them permanently logged in unless they log out, did that make sense?

Thanks
Jon
0
 

Author Comment

by:jalexan123
ID: 13543252
Also, do I need to place any code on each user accessable page or just in the login page?

Thanks
Jon
0
 

Author Comment

by:jalexan123
ID: 13543283
Actually about the cookie unset thing, I found this in Diablo84's comments :-

setcookie("autologin", "", time() - 3600);

But where exactly would I place that?

Thanks
Jon
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543285
Cookie lifetime is set in the setcookie method itself.

> setcookie("autologin", $cookiedata, time() + 31536000);

The 31536000 represents the number of seconds to expire. You can do it as :

setcookie("autologin", $cookiedata, time() + 60*60*24*30*12);

so the lifetime of the cookie is one year from the current time.

Dont forget to remove the cookie if the user logs out. Removing cookie can be done like this :

setcookie("autologin", "", time() - 3600);

you can notice the subtraction of 1 hour(60*60) from the current time denotes the cookie has been expired already.

>>  Also, do I need to place any code on each user accessable page or just in the login page?

You should have SESSION maintained for the user. Assuming you have a common file named "login.php" which is called in every authenticated page, you have to put the code (above cookie code) in login.php.

Structure is like this :

<?php

 if(isset($_COOKIE["autologin"])) {
   // call the cookie using the code given.
 }
 else {
  // first time login or cookie expired. Call with normal procedure.
 }

?>
0
 

Author Comment

by:jalexan123
ID: 13543308
We seem to have posted at the same time, yes login.php is in every authenticated page, but where do I put the

setcookie("autologin", "", time() - 3600);

Does that go in the same page and how does it know someone has logged out? There is a logout button.

Thanks
Jon
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543339
> There is a logout button.

Say logout.php is called when logout button is entered, put the code in logout.php
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543349
Including the secookie("autologin", "", time() - 3600); can be put anywhere in that logout.php but make sure it is fired. (not within any IF.. ELSE loop)

If unclear, post the action page of logout button (logout.php)
0
 

Author Comment

by:jalexan123
ID: 13543350
Ah cool, Cheers ldbkutty, I will do that!!!!

Anyway just one other thing about the encryption, is there anywhere I can find out about that, or is it easier to start a new question?

Cheers
Jon
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543351
typo... its setcookie... not secookie
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13543355
would be better if it is a new question :)
0
 

Author Comment

by:jalexan123
ID: 13543363
Cool!!! Will start one right now!! I tried the logout.php with the new line of code and it works great. Before when you used to signout it still showed the cookie but now it says not-set!

Thanks
Jon
0

Featured Post

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

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

Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
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.
The viewer will learn how to count occurrences of each item in an array.
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
Suggested Courses

770 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