Snippets, Tutorials

Store login information in cookie using jQuery

HTML code:

<form action="login.php" method="post" id="login">
<fieldset>
<legend>Login</legend>
<label for="username" class="label">Username</label>
<input type="text" name="username" id="username" class="text" maxlength="30" />
<label for="password" class="label">Password</label>
<input type="password" name="password" id="password" class="text" maxlength="30" />
<input type="checkbox" name="remember" id="remember" />
<label for="remember">Remember me</label>
<input type="submit" name="submit" value="Login" />
</fieldset>
</form>

Javascript code:

The first javacript snippet will be used to store username and password into cookie if 'Remember me' checkbox is ticked.

The second javacript snippet will be used to populate username and password fields with the details stored in cookie previously.

Uses jQuery library and jQuery cookie plugin.

Store into cookies

if ($('#remember').attr('checked')) {
var username = $('#username').attr("value");
var password = $('#password').attr("value");
// set cookies to expire in 14 days
$.cookie('username', username, { expires: 14 });
$.cookie('password', password, { expires: 14 });
$.cookie('remember', true, { expires: 14 });
} else {
// reset cookies
$.cookie('username', null);
$.cookie('password', null);
$.cookie('remember', null);
}

Read from cookies

var remember = $.cookie('remember');
if ( remember == 'true' ) {
var username = $.cookie('username');
var password = $.cookie('password');
// autofill the fields
$('#username').attr("value", username);
$('#password').attr("value", password);
}

Are you a developer? Want to get a promotion, work on interesting projects, land a high paying job at a tech company or stand out from the crowd?

Then this ebook is for you!

Career Guide for Software Developers

Career Guide for Software Developers

18 thoughts on “Store login information in cookie using jQuery

  1. This is great! Thanks so much. Hope it will continue.

    you can get interesting post about web usability and technology on my Web Usability Blog.

  2. Hi,

    My requirement is almost same where if user will check remember me once then he will get his username automatically in text box.

    I have used the same code, But for some reason it is not working in my asp.net mvc application. For your reference i am keeping my code which is as follows.

    Login
    Username

    Password

    Remember me

    if ($(‘#remember’).attr(‘checked’)) {
    var username = $(‘#username’).attr(“value”);
    var password = $(‘#password’).attr(“value”);
    // set cookies to expire in 14 days
    $.cookie(‘username’, username, { expires: 14 });
    $.cookie(‘password’, password, { expires: 14 });
    $.cookie(‘remember’, true, { expires: 14 });
    } else {
    // reset cookies
    $.cookie(‘username’, null);
    $.cookie(‘password’, null);
    $.cookie(‘remember’, null);
    }

    var remember = $.cookie(‘remember’);
    if (remember == ‘true’) {
    var username = $.cookie(‘username’);
    var password = $.cookie(‘password’);
    // autofill the fields
    $(‘#username’).attr(“value”, username);
    $(‘#password’).attr(“value”, password);
    }

    First time when page is loading username and password is coming as null. Even when i am putting username and password and do check “Remember me”, then also next time i am getting null value in both the field(username and password).

    Any help would be appreciated….

    Thanks in Advance…..

  3. Hi Daya, Did you have your input ids as “username”, “password” and “remember” in your login form? And are you storing the cookies on onsubmit event?

  4. Hi Eisabai,

    Thanks for your response. Yes I am using input id’s username(Textbox), password(textbox), remember(checkbox).

    But I am not storing the cookies onsubmit event. Can u please guide me that how i can store cookies on onsubmit event….

    Again thanks for your kind response..

    Looking for your positiver response.

  5. Hi… I need help, please… I have a error, below:

    jQuery is not defined
    jQuery.cookie = function(name, value, options)

    Help please…

  6. Don’t worry, was my mistake.
    Sorry :(

  7. No prob! Glad you got it sorted out.

  8. Terrific!

    Thanks for this.

  9. Hey, thanks for the code!

    Works a charm. Although isn’t it a bad idea to store the users password unprotected in a cookie?

    Is there any encryption that can be applied?

    B ;)

  10. Hi Ben,

    You can set the secure flag for the cookies so they are only transmitted via secured connections (SSL).

    For example:

    $.cookie(‘username’, username, { expires: 14, secure: true });

  11. Hey eisabai,

    That’s good to know regarding secure transmit of data, but as far as I understand it the cookie is stored locally, on the users machine, right?

    So you are storing the users password unencrypted in a cookie, which can be accessed and viewed.

    I was thinking more along the lines of MD5 cryptography for the password/string? see here: http://pajhome.org.uk/crypt/md5/

    B ;)

  12. Hi Ben,
    I agree it’s a good practice to encrypt cookies that contain sensitive information like username and password. Thank you for the link. :)

  13. Hey,

    Been looking into this a bit more.

    There’s a jQuery MD5 script here: http://www.semnanweb.com/jquery-plugin/md5.html

    I think storing the encrypted MD5 password in the cookie then matching that to the password in the db via an MD5 comparison.

    So as an example jQuery to PHP query:

    jQuery:
    // get user name and passwrord values
    var user = $(“#user_name”).val();
    var pwd = trim( $(“#user_pwd”).val() );

    // make ajax call with data
    $.ajax({
    type: “POST”,
    url: “login.php”,
    data: ‘user=’+ user + ‘&pwd=’ + $.md5( pwd ),
    success: loginResponse
    });

    php:

    // get password from post vars
    $pwd = mysql_real_escape_string( $_POST[‘pwd’] );

    // query string – using sql md5()
    $query = “SELECT `user_password` FROM `tbl_users `WHERE MD5( `user_password` ) = ‘”.pwd.”‘” ;

    // now run query…

    On a successful match you can then store you cookie data, storing the password as md5.

    I think this is a good way to do it. :)

  14. Just wanted to say that I agree with the argument that storing usernames and passwords in cookies is not good practice, even if they are encrypted with something like md5.

    If you’re using php a better way to authenticate would be to use sessions and have the server set a variable in the $_SESSION array. You might also want to set a initial login timestamp value in that array, as well as a “last action” timestamp, and write your security rules based on these.

    Another way of doing security in an *AMP environment is to store that data in a database table (currently logged in users) and use the session key (which is stored in a cookie or can be appended to the url if cookies are off). This is the method that expression engine uses and is quite secure.

    You can then set up your rules on the server side so users are prompted for passwords more or less frequently, according to the level of security you need.

Comments are closed.

Twitter
LinkedIn
YouTube
Instagram