not staying logged in

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
m3rajk
DevNet Resident
Posts: 1191
Joined: Mon Jun 02, 2003 3:37 pm

not staying logged in

Post by m3rajk »

ok. actually i'll make this a two-in-one.


there was an issue with logins before. with your help i was able to fix it, so maybe i can get both fixed now.


first, and way more importantly, is the one that the 2 friends to sign up last are having. both using M$ internet explorer. both are not staying logged in.

i cannot duplicate this. no one who signed up before them has the issue. they are successfully singing in, it's just not keeping. default login time is two min. they are def not waiting long enough for timeout.



secondly, i'm wondering how one can make a cookie which will stay in cache after one closes out a browser. this way i can make the cookies persist for those that don't want to be bothered with signing in each time they start up the browser

i don't see how to do it with setcookie()

the following code is ALL the code that sets cookies.

Code: Select all

[joshua@Ashes includes]$ cat fyd.funcs.php | more
<?php
# functions used by multiple FindYourDesire pages

function cookies($action){ # inserts cookies
  include("/home/joshua/includes/fyd.altincs.php"); # includes file

  if($action==='join-1'){ # make & set the confirmation code

    $conf=md5(uniqid(microtime(),1)); # make unique id
    $expire=time()+24*60*60; # set expiration an hour from now
    setcookie('confcode', $conf, $expire); #create cookie

  }elseif($action==='join-3'){

    $un=$_POST['un']; $pw=md5($_POST['pw']); # set the username and password into cookies, pw is masked
    $expire=time()+60*60; # set expiration an hour from now
    setcookie('un', $un, $expire); # username
    setcookie('pw', $pw, $expire); # pw
    setcookie('utds', 'm/d/Y H:i:s', $expire); # time display
    setcookie('gmto', '-5', $expire); # gmt offset

  }elseif($action=='logout'){ # make all cookies expire

    $expire=time()-(60*60*24*7); # set expire to 60 sec*60 min*24 hrs* 7 days ago (make sure a lagging computer will kill it
 even if my host is in new zealand)
    setcookie('un', NULL, $expire); # makes user name expire & sets it to NULL incase their computer errs
    setcookie('pw', NULL, $expire); # makes password expire & sets it to NULL incase their computer errs
    setcookie('login', NULL, $expire); # makes login expire & sets it to NULL incase their computer errs
    setcookie('utds', NULL, $expire); # makes the tds expire & sets it to NULL incase their computer errs
    setcookie('gmto', NULL, $expire); # makes the gmt offset expire & sets it to NULL incase their comp errs

  }elseif($action=='update'){ # updates cookies (keeping you logged in) & returns waiting messages (optional)

    if(isset($_COOKIE['login'])&&($_COOKIE['login'])){ # we're logged in

      $ims=array(); # empty array for any ims we might find unread
      $db=mysql_connect($host, $login2, $pass2) or die("cannot access mysql"); # get the sql connection
      $fyd=mysql_select_db('findyourdesire', $db) or die("cannot connect to db"); # select the db
      $un=$_COOKIE['un']; $pw=$_COOKIE['pw']; # what we wont change on-the-fly
      $fprefs=mysql_query("SELECT uid, gmt_offset, tds, login_duration, msgs FROM users WHERE username='$un' AND password='$
pw'", $db); # get the prefs
      if(mysql_num_rows($fprefs)>0){ # we can update the cookies
        $prefs=mysql_fetch_array($fprefs); $gmto=$prefs['gmt_offset']; $utds=$tdc[$prefs['tds']]; 
        $duration=$durr[$prefs['login_duration']]; $accepts=($prefs['msgs']*1); $uid=$prefs['uid'];
        $expire=(time()+($duration*60));
        setcookie('un', $un, $expire); # set username
        setcookie('pw', $pw, $expire); # set password
        setcookie('login', 1, $expire); # set login
        setcookie('gmto', $gmto, $expire); # set the gmt offset
        setcookie('utds', $utds, $expire); # set the time display style
        $active=gmdate("Y-m-d H:i:s", time());
        $update=mysql_query("UPDATE users SET last_activity='$active' WHERE username='$un'", $db); # try to update users (we
 don't really care if it fails)

        if($accepts){ # person accepts ims

          if($accepts>5){ # the user wants them ALL
            $fims=mysql_query("SELECT msg_id, from_un FROM msgs WHERE to_id='$uid' AND viewed='0'", $db);
            while($gimid=mysql_fetch_array($fims)){ # while there's ims
              $ims[]=$gimid; # record the msg_id
            }

          }else{ # user wants $accepts amount
            $fims=mysql_query("SELECT msg_id, from_un FROM msgs WHERE to_id='$uid' AND viewed='0' ORDER BY msg_id ASC LIMIT 
$accepts", $db);
            while($gimid=mysql_fetch_array($fims)){ # while there's ims
              $ims[]=$gimid; # record the msg_id
            }
          }
        }
      }
    } # end cookie updating
    return $ims;
  }
}
...
?>
noting else in that sets cookies. the page begining functionscall cookies('update'); to get the ims and update the cookies. i modified the login so it wouldn't do that (made a new page starte fot he success call)

Code: Select all

[joshua@Ashes fyd]$ cat login.php
<?php
include("/home/joshua/includes/fyd.incs.php"); # includes file
# variables used
$login=FALSE; $title='Login Page'; $error=FALSE; $linfo='';$expire='';

if(isset($_POST['un'])){ # check the db if this isn't the first loading of the page
  $un=$_POST['un']; # what was the passed username?
  $pass=MD5($_POST['pass']); // what was the given password
  $db=mysql_connect($host, $login2, $pass2) or die("cannot access mysql"); # connect to the database
  $fyd=mysql_select_db('findyourdesire', $db) or die("cannot connect to db"); # select the db
  $lookup=mysql_query("SELECT uid, site_access, login_duration, gmt_offset, tds FROM users WHERE username='$un' AND password='$pass'", $db);// find user by username/pass combo
  if(mysql_num_rows($lookup)){ // we have a user (username is unique, it can only be 1 or 0 returned)
    $info=mysql_fetch_array($lookup); # get all the info associated with the user
    $sa=$info['site_access']; // find the site access
    if((contains($sa, $regulars))||(contains($sa, $desireds))){ # if you're not suspended
      $login=TRUE; $duration=$info['login_duration']; $uid=$info['uid']; # set login, cookie duration, uid
      $gmto=$info['gmt_offset']; $utds=$tdc[$info['tds']]; # set the gmt offset & time display
      $now=gmdate("Y-m-d H:i:s", time()); $currip=$_SERVER['REMOTE_ADDR']; # get the time/new ip
      $update=mysql_query("UPDATE users SET last_login_ip='$currip', last_login_date='$now' WHERE uid='$uid'", $db); # update login date and ip
      $expire=time()+(60*$durr[$duration]); # set expiration by formula time()+seconds*minutes*hrs*days*yrs
      setcookie('un', $un, $expire); # set username
      setcookie('pw', $pass, $expire); # set password
      setcookie('login', 1, $expire); # set login
      setcookie('gmto', $gmto, $expire); # set the gmt offset
      setcookie('utds', $utds, $expire); # set the time display style
      bgnlpg($title); nav2(); success($un); clspg(); # show the successful login page
    }else{ bgnpg($title); nav(); login($un, TRUE, 3); clspg(); } # the user is suspended
  }else{ bgnpg($title); nav(); login($un, TRUE, 1); clspg(); } # there was no user by that name/password
}else{ bgnpg($title); nav(); login('', FALSE, 0); clspg(); } # no failed login attempt


/* *********************************
   ** create the appropriate page **
   ********************************* */
function success($un){
  include('/home/joshua/includes/fyd.altincs.php'); # includes file
  echo <<<END
      <h1>Welcome back $un!</h1>
      <p>Please choose where to go next</p>
      $tsw100
          <tr>
            <td class="center"><a href="index.php">Home</a></td>
            <td class="center"><a href="forums.php">Forums</a></td>
            <td class="center"><a href="search.php">Search</a></td>
          </tr>
      </table>

END;
}

function login($un, $err, $user){ // login page, username is remembered if there was a failed attempt
  include('/home/joshua/includes/fyd.altincs.php'); # includes file
  if($err){ # there was an error
    if($user==1){ # there is no such user
      echo '      <font color="#ff0000"><h1>Your Username or Password is wrong. Please check your spelling and try again</h1></font>';
    }else{ # you're suspended or updating your email
      echo '      <p>Your email is unvalidated or you have been suspended, please check the forums. The two times you are not allowed to login are when your e-mail address is unvalidated or you have been suspended. In the latter case there should be a thread in either the Fakes or Problems/Comments/Suggestions forum stating what the problem is.</font></p>';
    }
  }
  if($err){$un=$_POST['un'];}else{$un='';} # set un's value
  echo <<<END
      <p>&nbsp;</p><p>&nbsp;</p>
      <form action="{$_SERVER['PHP_SELF']}" method="POST">
        $tsnw
            <tr><td>Your Member Name</td><td><input type="text" name="un" size="15" maxsize="15" value="$un"></td></tr>
            <tr><td>Your Password</td><td><input type="password" name="pass" size="15" maxsize="15"></td></tr>
            <tr><td><a href="pass.php">Lost Your PW?</a></td><td><input type="submit" value="Login!"></td></tr>
        </table>
      </form>
END;
}
?>[joshua@Ashes fyd]$
the success used to call the normal page begining functions (bgnpg()) which updates the cookies (figured that might be the issue)
chris22
Forum Newbie
Posts: 11
Joined: Tue Apr 22, 2003 9:45 pm

Post by chris22 »

You're doing waaaaay too much work with cookies. What for? Use sessions instead. That's one temporary cookie that goes away automatically when the browser is closed and handles all of your user specific variable needs. Set only one permanent cookie with the information necessary to automatically start the session, if the user desires it.

This is a demo I wrote to show a bug regarding cookies that appeared while beta testing Opera, but it should illustrate a primitive auto-login:

Code: Select all

<pre>
<?
// this file is named 'cookietest.php'

print "<strong>Post:</strong>\n";
print_r($_POST);

if (sizeof($_POST) > 0) {
	print "Attempting to set a cookie.  The \$_COOKIE array will appear empty until this page is visited again or refreshed.\n";
	setcookie('test', 'This is a test cookie', mktime(date('h'), date('i'), date('s'), date('m'), date('d'), date('y') + 1), '/', $_SERVER['HTTP_HOST']);
}

if (isset($_COOKIE)) {
	print "<hr /><strong>Cookie:</strong>\n";
	print_r($_COOKIE);
	
	if (isset($_COOKIE['test'])) {
		print "Test cookie detected, attempting to start the session.  PHPSESSID may or may not show up as a cookie.  It will delete itself when your browser is closed.\n";
		session_start();
		
		if (!isset($_SESSION['test'])) {
			$_SESSION['test'] = 'Session started!';
		}
	}
}

if (isset($_SESSION)) {
	print "<hr /><strong>Session:</strong>\n";
	print_r($_SESSION);
}

if (!isset($_COOKIE['test'])) {
?>
<form method="post" action="cookietest.php">
No test cookie detected.  Please make sure your browser is set to accept cookies.

<input type="submit" name="set_cookie" value="Set Cookie" />
</form>
<?
}
?>
</pre>
Just set the user name or id and their encrypted password as a serialized array in a permanent cookie for autologin (allowing many variables to be placed inside a single cookie), and have the rest of the necessary variables be session variables.
m3rajk
DevNet Resident
Posts: 1191
Joined: Mon Jun 02, 2003 3:37 pm

Post by m3rajk »

i can't change session lengths in sessions. iknow ppl that visit sites from work, and when i'm at a public terminal, i'd want it shorter. when at home, even if you share, you want more time. this way i can have the user adjust and with the next page load change their login length.

the low end and default both 2 min. i've got it set at 30 min for me... i've tried closing out the browser and opening back up. both ie (6.0) and mozilla (1.3.1) ... doesn't stay logged in
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

Usually someone can 'spot the problem' by looking at the code. Don't take me wrong, but in this case its difficult due to the fact that linebreaks and spaces are somewhat distorted.

Good idea about using different expire time based on where the user is located. But you would still be able to use setcookie once, containing the information you need to get around.
serialize() is one example.

Debug it adding echo's before some of the places where you think might be the issue, and see what those generate (or doesnt).
Post Reply