Jump to content

I need help figuring out how to add cookies to my login script with sessions


Recommended Posts

Okay here is my problem i been stuggling with. I have a login script i use regularly that uses sessions. Actually some might recongize it because its from one of Eric Rosebrocks books.

Any how the script works find with out cookies but now i want to add that famouse check box in the login box that says remember me. I havent worked much with cookies so im struggling on how to get it to work. Below is my code for the login, and validation process. I just cant figure out how or where to add cookies to my current code to add this feature.

Login in form. Basicly it checks to see if sessions are set and weather to display login form or not.
[code]
<?php
if($_SESSION['login'] != true){
?>
<form action="/login.php" method="post">
<p><label for="1">Username:</label><input type="text" id="1" name="username" /></p>
<p><label for="2">Password:</label><input type="password" id="2" name="password" /></p>
<p>
<input type="hidden" name="req" value="validate" />
<input type="submit" name="submit" value="Go!" />&nbsp;Remember me!<input type="checkbox" name="cookie" checked="checked" />
</p>
</form>
<p>Not a member yet?&nbsp;<a href="/join.php">Register Here</a></p>
<p>Lost Password?&nbsp;<a href="/lostpw.php">Click Here</a></p>
<?php
}else{
echo '<p>Welcome '.$_SESSION['username'].'</p>'.
        '<p>To Logout <a href = "logout.php"> click here</a></p>';
}
?>

[/code]

The validation process where I want to set cookies somehwere.
[code]
$validate = @mysql_query("SELECT * FROM members WHERE username='{$_POST['username']}' AND
password = md5('{$_POST['password']}') AND verified = '1'");

if(mysql_num_rows($validate) == 1){
while($row = mysql_fetch_assoc($validate)){
$_SESSION['login'] = true;
$_SESSION['userid'] = $row['id'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
$_SESSION['email_address'] = $row['email_name'];
$_SESSION['username'] = $row['username'];

if($row['admin_access'] == 1){
$_SESSION['admin_access'] =true;
}
$login_time = mysql_query("UPDATE members SET last_login=now() WHERE id='{$row['id']}'");
}
header("Location: /index.php");
}else{
myheader(" - Login Failed!");
echo '<p>Login Failed</p>';
echo '<p>If you have already joined our website, you may need to validate '.
'your email address. Please check your email for instructions.';
footer();
}

[/code]

If someone has any ideas on how to modify my code to add a remember me feature please feel free to modify my code and show me how. Im a better visual learner then reader so if i see what is being explained rather then text I will get a better grips on what to do. Thanks for any help someone can give me .
The form looks good, but what information do you want to put into the cookie?  Their userid?

Try something like this:

[code]<?php
$validate = @mysql_query("SELECT * FROM members WHERE username='{$_POST['username']}' AND password = md5('{$_POST['password']}') AND verified = '1'");

if(mysql_num_rows($validate) == 1){
  while($row = mysql_fetch_assoc($validate)){
      $_SESSION['login'] = true;
      $_SESSION['userid'] = $row['id'];
      $_SESSION['first_name'] = $row['first_name'];
      $_SESSION['last_name'] = $row['last_name'];
      $_SESSION['email_address'] = $row['email_name'];
      $_SESSION['username'] = $row['username'];

      if($row['admin_access'] == 1){
        $_SESSION['admin_access'] =true;
      }

      // This has been added
      if (isset($_POST['cookie'])){
        setcookie("authenticated", $row['id'], time()+604800, "/", "domain.co.uk"); // set to expire in 7 days
      }
     
      $login_time = mysql_query("UPDATE members SET last_login=now() WHERE id='{$row['id']}'");
  }
  header("Location: /index.php");
}
else{
  myheader(" - Login Failed!");
  echo '<p>Login Failed</p>';
  echo '<p>If you have already joined our website, you may need to validate '.
  'your email address. Please check your email for instructions.';
  footer();
}
?>[/code]

This will add the cookie to the domain if they've ticked the checkbox.  You'll need to change the condition on your pages that check for login though, as they'll need to check for [code=php:0]$_COOKIE['authenticated'][/code] and [code=php:0]$_SESSION['login']
[/code]

Regards
Huggie
thanks. Basicly im trying to store the same info in my cookies as my sessions. The sessions part works fine if they dont want to be remember, just gotta figure out the cookie part so when they come back to the site they dont have to login if they choose.

So to modify my login form i have to add something like
[code]
if($_SESSION['login'] != true || $_COOKIE['login'] = !true){
      // Show form
}else{
      // check cookie info against database for correct username and password
}
[/code]

Is that what you mean when you say modify my login form?
Hmmmm okay i think i got the cookie part work but came across a session problem. If i login without the cookie option everything works fine it sets the session and i can go on as usual.

If i set the cookie option and login all my sessions and cookies are working. Now the problem comes when I close the browsers and open it again to check to see if my cookies are working and they are but my session variables do not seem to get set. Which in the end is what I will need.

The only purpose the cookies should server really is to just login the user when they return to the site, and then from there your session variables should take over. Correct? Atleast that is what im trying to accomplish but im now struggling to figure out why they arent here is my code I did so far if anyone can point out why my session variables $_SESSION['username'] And $_SESSION['login'] are empty when the user returns can you give me a suggestion how to fix it.

index page
[code]
<?php
session_start();
session_name('2am-designs');
header("Cache-control: private"); // Fix for IE
include $_SERVER['DOCUMENT_ROOT'].'/inc/database.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<?php
if($_COOKIE['login'] == true || $_SESSION['login'] == true){
if(isset($_COOKIE['login'])){
$username = $_COOKIE['username'];
$password = $_COOKIE['password'];
$validate = @mysql_query("SELECT * FROM members WHERE username='$username' AND
        password = md5('$password')");
if(mysql_num_rows($validate) == 1){
if(!isset($_SESSION['login'])){
$_SESSION['login'] = $_COOKIE['login'];
$_SESSION['username'] = $username;
// More Session variables here
}// End IF
}// End If
}// End If
echo '<p>Session Login Value = '.$_SESSION['login'].'</p>';
echo '<p>Session ID Value = '.session_id().'</p>';
echo '<p>Session Username = '.$_SESSION['username'].'</p>';
echo '<p>Cookie Login Value = '.$_COOKIE['login'].'</p>';
echo '<p>Cookie Username = '.$_COOKIE['username'].'</p>';
echo '<p>Cookie Password = '.$_COOKIE['password'].'</p>';
echo '<a href="/test/destroy.php">Destroy</a>';
}else{
?>
<form action="validate.php" method="post">
<p><label>Username</label><input type="text" name="username" /></p>
<p><label>Password</label><input type="password" name="password" /></p>
<p><label>Set Cookie</label><input type="checkbox" name="remember" /></p>
<p><input type="submit" value="Go!" name="submit" /></p>
</form>

<?php } // End Else ?>
</body>
</html>
[/code]
This should be stright forword first it checks for a $_COOKIE['login'] OR $_SESSION['login'] to be true.Then if the cookie is set then it uses that info to check user info against the database. Then inside that it checks to see if session is not set and if not sets my session variables. Or it shows the form to login.

validate login info
[code]
<?php
session_start();
session_name('2am-designs');
header("Cache-control: private"); // Fix for IE
include $_SERVER['DOCUMENT_ROOT'].'/inc/database.php';
$validate = @mysql_query("SELECT * FROM members WHERE username='{$_POST['username']}' AND
        password = md5('{$_POST['password']}')");
if(mysql_num_rows($validate) == 1){
while($row = mysql_fetch_assoc($validate)){
  $_SESSION['login'] = true;
  $_SESSION['userid'] = $row['id'];
  $_SESSION['first_name'] = $row['first_name'];
  $_SESSION['last_name'] = $row['last_name'];
  $_SESSION['email_address'] = $row['email_name'];
  $_SESSION['username'] = $row['username'];

  if($row['admin_access'] == 1){
$_SESSION['admin_access'] =true;
  }
  // Check For Cookie Option
  if(isset($_POST['remember'])){
setcookie("login",true,time()+60*60*24*100,"/");
setcookie("username",$row['username'],time()+60*60*24*100,"/");
setcookie("password",$row['password'],time()+60*60*24*100,"/");  
  }
      $login_time = mysql_query("UPDATE members SET last_login=now() WHERE id='{$row['id']}'");  
} // End While
header("Location: /test/index.php");
}else{
echo "Invaild Username Or Password";
}
?>
[/code]


Any help as to what im doing wrong I would appreciate it my brain is feels like mush now trying to solve this problem. Thanks
OK, here's some code, it's stripped down to basics and just has comments where you can fill bits in yourself, but a few basics, my login form is called login.php, my secure content page is called menu.php.

[b]menu.php[/b]
[code]<?php
// Start Session
session_start();

// Check if my user details have been stored in session vars yet
if (!isset($_SESSION['username'])){
  header("Location: login.php");
}
else {
  echo "You are logged in {$_SESSION['username']}, welcome to the main menu...\n";
}
?>[/code]

You could even put the first few lines into a header file and just use an include to include it on each page.

[b]login.php[/b]
[code]<?php
// Start Session
session_start();

// Connect to db
include('connect.php');

// Under what pretence are we here, redirected, or just submitted the login form
if (!isset($_POST['submit'])){

  // the form hasn't been submitted so we just landed here or were directed here, so lets get details
  if (isset($_SESSION['username'])){
      // We must have returned here having already logged in once this session
      header("Location: menu.php");
  }
  else if (isset($_COOKIE['authenticated']) && !isset($_SESSION['username'])){
      // If we have the remember me cookie, but it's the first time we've logged in this session
      $sql = "SELECT * FROM users WHERE id = '{$_COOKIE['authenticated']}'";
      $result = mysql_query($sql);
      $u = mysql_fetch_array($result, MYSQL_ASSOC);
      $_SESSION['username'] = $u['username'];
      $_SESSION['realname'] = $u['name'];
      $_SESSION['email'] = $u['email_address'];
      header("Location: menu.php");
  }
  else {
      // We don't have a cookie set at all, we need to login
      // -- put your form code here --
  }
}
else {
  // The form's been submitted, so process it
  // Get our username and password from the form using $_POST variables
  // -- put your processing code here --

  // Check them against the database for successful login
  $sql = "SELECT * FROM users WHERE username = '{$_POST['username']}' AND password = '{$_POST['password']}'";
  $result = mysql_query($sql);

  // Did the user authenticate OK?
  if (mysql_num_rows($result) == 1){ // Authenticated OK
      $u = mysql_fetch_array($result);
      $_SESSION['username'] = $u['username'];
      $_SESSION['realname'] = $u['name'];
      $_SESSION['email'] = $u['email_address'];
     
      // Now comes the important cookie part
      // if 'remember_me' is set, cookie expires in 30 days, if it's not, then expires at end of session
      $expire = isset($_POST['remember_me']) ? time()+60*60*24*30 : null;

      // Set the cookie using the above $expire variable
      setcookie("authenticated", $u['id'], $expire, "/", "yourdomain.co.uk");
      header("Location: menu.php");
  }
  else { // Not authenticated
      // Print your form code
      // -- put your form code here --
  }
}
?>[/code]

Now you'll see some repeated code here that could be put into functions, such as echoing the form code and retrieving details from the database, but I wanted to give you the gist of the code, not the intricacies of it.

Regards
Huggie
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.