William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP: remember me

PHP: remember me functionality

In the login form, generally there is a remember me checkbox to indicate if remember username/password to avoid repeatly input everytime when login.

The following I list my version which gives minimum codes to do remember me function. I use jQuery’s cookie function to save username/password in client side’s cookie cache.

<script src="jquery-1.5.1.min.js"></script>
<script src="cookie.js"></script>
<script>
$(document).ready(function() {
 if( $.cookie('[app][username]') && $.cookie('[app][userpass]') ) {
  $('#username').val($.cookie('[app][username]'));
  $('#password').val($.cookie('[app][userpass]'));
  $('#rememberme').attr('checked', true);
 }
 else {
  $('#rememberme').attr('checked', false);
 }
});
</script>

<form id="login_form" action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<div>
  <label for="username">Username:</label>
  <input id="username" name="username" type="text" />
</div>
<div>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" />
</div>
<div>
  <label for="rememberme">Remember Me</label>
  <input id="rememberme" name="rememberme" type="checkbox" />
</div>
<input type="submit" value="Submit">
</form>

The above codes list a login form which includes username, password, and remember checkbox. and add javascript rememebrme codes.
The following is when user clicks the form to submit, PHP codes will save information to cookie array.

<?php
 $username = mysql_real_escape_string(trim($_POST['username']));
 $password =  $_POST['password'];
 $rememberme = isset($_POST['rememberme']) ? true : false;

 // check Database table to search this user's information; 
 // the return value is kept in $total.
 if ($total>0) {
  $username = ucfirst(strtolower($username));
  if($rememberme) {
   $expire = time() + 1728000; //Expire in 20 days
   setcookie('[app][username]', $username, $expire);
   setcookie('[app][userpass]', $password, $expire);
  }
  else {
   setcookie('[app][username]', NULL);
   setcookie('[app][userpass]', NULL);
  }
?>

When user selects the checkbox and successfully login, the login information will be saved in client’s cookie array $.cookie[app][username] and $.cookie[app][userpass]. Everytime when login form is called, the js will init the form to fill up username/password with the cookie array values.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: