Jump to content

[SOLVED] cookies to stay logged in


aebstract

Recommended Posts

First of all, this is my first time doing anything with cookies, though it seems to be easy enough. Problem is, they aren't doing what they should. I log a user in with a session and keep them on with that. What I want to do is, if they choose to stay logged in, set their session id with a cookie. When they come back, if the session id isn't set, set it with that cookie. I've read that when you close a browser it will clear/reset cookies but if you set an expiration time then it will be saved, so I have this:

 

login page

if(mysql_num_rows($result) == 0)
    {
      $error .= "The pasword you entered did not match the plant location you chose.";
    }
    else
    {
      $worked = mysql_fetch_array($result);
      $_SESSION["id"] = $worked['plant'];
$uid=$worked['user_id'];
$lastlogin= date("m/d/Y g:i A");

    mysql_query("UPDATE users SET lastlogin='$lastlogin' WHERE user_id=$uid LIMIT 1") or DIE(mysql_error());


$postsessid = $worked['plant'];
setcookie ('savedid', '$postsessid', time()+5256000);

      header("Location: /accounthome/");
      exit;
    }

 

 

and the index where it reads this

if (!isset($_SESSION[id])) {
if (isset($_COOKIE['savedid'])) {

      $_SESSION["id"] = $_COOKIE['savedid'];

}
}

Link to comment
Share on other sites

There is a good chance the session attached to that ID no longer exists on the server.

 

If you want to create a remember me function, the best thing to do is to store the user's ID or username in a cookie along with a unique token.  You store this same unique token in the user's row in the users table.

 

When a guest visits your site, you check for the username and token in the cookie and see if they match in the database as well.  If they do, you can auto-login that user.

 

Do not store the user's password or an easily guessed value in the cookie as clever people will figure it out.  You want the token to be unique and constantly changing so the chances of someone guessing the proper token for a username is slim to none.

Link to comment
Share on other sites

I set the session by using the users unique id that they have, ie; 1,2,3,4,5 etc. With what you said, I made a unique 10-13 char. key for verification, though I guess it is just a little extra security, not 100% needed. I just can't get it to set a session with the stored id in the cookie.

 

on the login page:

if (isset($_POST['stayloggedin'])) {
$postsessid = $worked['plant'];
setcookie ('savedid', '$postsessid', time()+5256000);

$numchars = rand(12,15);
$chars = explode(',','a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9');
$random='';
for($i=0; $i<$numchars;$i++)  {
  $random.=$chars[rand(0,count($chars)-1)];
}

setcookie ('savedkey','$random', time()+5256000);

    mysql_query("UPDATE users SET randomkey='$random' WHERE user_id=$uid LIMIT 1") or DIE(mysql_error());

}


      header("Location: /accounthome/");
      exit;
    }

 

the checkbox (I don't use them often, maybe I messed it up)

<input type="checkbox" name="stayloggedin" />

 

the index

if (!isset($_SESSION[id])) {
if (isset($_COOKIE['savedid'])) {

$result = mysql_query("SELECT * FROM `users` WHERE `plant` = '$_COOKIE[savedid]' AND `randomkey` = '$_COOKIE['savedkey']'")
      or die("Query error: ".mysql_error());

      if(mysql_num_rows($result) == 0)
      {
        echo "Cookies modified or invalid.";
      }
      else
      {
        $worked = mysql_fetch_array($result);
        $_SESSION["id"] = $worked['plant'];
  	$uid=$worked['user_id'];
  	$lastlogin= date("m/d/Y g:i A");

      mysql_query("UPDATE users SET lastlogin='$lastlogin' WHERE user_id=$uid LIMIT 1") or DIE(mysql_error());


  $postsessid = $worked['plant'];
  setcookie ('savedid', '$postsessid', time()+5256000);

  $numchars = rand(12,15);
  $chars = explode(',','a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9');
  $random='';
  for($i=0; $i<$numchars;$i++)  {
    $random.=$chars[rand(0,count($chars)-1)];


  setcookie ('savedkey','$random', time()+5256000);

      mysql_query("UPDATE users SET randomkey='$random' WHERE user_id=$uid LIMIT 1") or DIE(mysql_error());

}

      $_SESSION["id"] = $_COOKIE['savedid'];

}
}

 

Link to comment
Share on other sites

Okay, I know I am setting the cookie correctly. My login script sets a session like so:

 

      $_SESSION["id"] = $worked['plant'];

 

and doesn't have a problem. I looked in my cookies for my browser, I see cookie "savedid" with content "92" which is correct, and the value of $worked['plant']. With this said, how come when I visit the site after reloading the browser, I am not logged in with this script in my index:

 

$cookieid = $HTTP_COOKIE_VARS["savedid"];

	if (isset($_SESSION[id])){ include "connect.php";

	} elseif (isset($cookieid)) {

	$_SESSION["id"] = $cookieid;
	include "connect.php";
setcookie ('savedid', $cookieid, time()+5256000);
	}

Link to comment
Share on other sites

First, don't use $HTTP_COOKIE_VARS as it is deprecated.  Use $_COOKIE instead.

 

You should also be aware that cookies are set for the domain and that http://yoursite.com and http://www.yoursite.com are two different domains.  So make sure you are not setting the cookie on a yoursite.com URL and then trying to read it on a www.yoursite.com URL.

 

The best thing to do when you are having problems with something is to simplify it into a "proof of concept" script.  Create a folder called test and create individual scripts inside it, where each script is a single proof of concept.

 

set_cookie.php - sets a cookie value

read_cookie.php - looks for the value and displays it

delete_cookie.php - removes the cookie

 

You can create those as a single script if you think you can handle it.  But the point of a proof of concept is to keep it simple.  If all you are trying to do is set a cookie and it's not being set, you don't have a lot of other crap in your way to bog you down.

 

To implement a "remember me" feature you have to do two things.

 

When a user logs into the site:

  • Does the user have "Remember me" checked?
  • No - Log in as normal (via sessions)
  • Yes - Create a unique key for the user.  Store this unique key in the user's row in the database.  Store encrypt(user_name) and encrypt(unique_key) in the cookie.  Log the user in as normal (via sessions)

 

Anytime a user visits your site and is not already logged in:

  • Does the user have a cookie with the user_name and unique_key values?(
  • No - This is not a remember me user, treat as a guest.
  • Yes - This is a remember me user.  Get the cookie values and decrypt.  Try to SELECT the matching row from the database.  If no row is found, do not log the user in.  If a row is found, log the user in via sessions.

Link to comment
Share on other sites

Okay I have all of those bottom features set up, though about the domain being exact everytime.. Is there any work around for that? If I go to domain.com and then when I go to type it back in I see it pop up below as http://domain.com and click it, I won't be logged in? Anyway around that? Would the best thing be to create a cookie for each domain at once?

Link to comment
Share on other sites

You can create a redirect rule in httpd.conf or an .htaccess file to redirect all requests without a www to the domain with www.  You will have to do this for each of the sub-folders of your site that contain URL-accessible scripts unless you are sending all requests through a single index.php via mod_rewrite.

Link to comment
Share on other sites

if (isset($_POST['stayloggedin'])) {
$postsessid = $worked['plant'];
setcookie ('savedid', $postsessid, time()+5256000, "https://berryequipment.net/");
setcookie ('savedid', $postsessid, time()+5256000, "https://www.berryequipment.net/");

 

Here is the cookie being set now, and it does so. I still can't get to stay logged in. My index.php has a little script that if you aren't on https that you get redirected to it, so that is why I put the https in front of both, and I could get it rewrote with the www. but the thing is that it still isn't working with either cookie atm.

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.