PHP: remember me
Blogs20122012-01-31
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.
http://jquery-1.5.1.min.js
http://cookie.js
$(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);
}
});
<form id="login_form" action="<?=$_SERVER['PHP_SELF'];?>" method="post">
Username:
Password:
Remember Me
<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.
