Use cookies to save user login status-preliminary implementation

Source: Internet
Author: User
Tags visibility

Saving the user's login status is a lot of Web sites will use, generally use session, database or cookies and sessions of the combination of methods, here we understand the cookie method to save the user login status.

Cookies are a way for servers or scripts to maintain information on client workstations under the HTTP protocol. A Cookie is a small text file saved by a WEB server on a user's browser (client) that can contain information about the user. The Web site can access Cookie information whenever the user is linked to the server.
At present some cookies are temporary and some are persistent. A temporary cookie saves a specified amount of time on the browser and is purged by the system once the specified amount of time is exceeded.
The persistent cookie is saved in the user's cookie file and can still be invoked the next time the user returns. Save cookies in a cookie file, some users worry that the user information in the cookie is stolen by some ulterior motives, causing some damage. In fact, users outside the site cannot cross the site to get Cookie information. If you block cookies because of this concern, you will definitely deny access to many site pages. Because, many WEB site developers today use cookie technology, such as the use of Session objects without the support of cookies.

Here, for the last time I did the Ajax login page to add cookies to save the login status of the operation ...

First, let's introduce cookies to read and write:

Document.cookie = "Cookie name =" + Value + "; expires=" + Effective time;
Where the Expires value represents the valid time of the cookie.

Write Cookie
var exp = new Date ();
Exp.settime (Exp.gettime () + 1000 * 60 * 60 * 24); This means save 24 hours
Document.cookie = "music_identify=" + ID + "; expires=" + exp.togmtstring ();

Read cookies: Because Document.cookie returns a string containing all cookies stored locally in the current domain, we need to segment the cookie string to find out what we need, and here is a function to get the cookie :

/* Get the specified cookie
/function GetCookie (name) {
    var strcookie = document.cookie;
    var Arrcookie = Strcookie.split (";");
    for (var i = 0; i < arrcookie.length i++) {
        var arr = arrcookie[i].split ("=");
        if (arr[0] = = name) return
            arr[1];
    }
    Return "";
}

We first split the cookie string obtained by Document.cookie to get a record of one piece, and then we split it by "=", in which case the incoming name value equals the string preceded by the "=" number, The cookie record we're looking for is that one, and then the string is returned, otherwise the empty string is returned.

After the introduction of reading and writing, we can start to simulate the user login, and in the cookie to save the user's login information

/* Ajax Login/function Ajaxlogin (ID, pass, classes) {var xmlhttp; if (window.
    XMLHttpRequest) {//code for ie7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest ();
    else {//code for IE6, IE5 xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP");

    } xmlhttp.open ("Get", "pages/loginbynav.php?user_id=" + ID + "&user_pass=" + Pass, false);
            Xmlhttp.onreadystatechange = function () {if (xmlhttp.readystate = = 4 && xmlhttp.status = 200) {
                if (xmlhttp.responsetext!= 0) {var Textarray = xmlhttp.responseText.split ("|"); document.getElementById ("InputBox"). InnerHTML = " 

Referring to the contents of the previous post, we modified it to add the login information to the cookie after the login was successful, and set the expiration date to 24 hours, so that after the user successfully logged in, the information is automatically saved to the cookie, we look in the browser

OK, the first step is done.

The next step is when the user refreshes the page, or leaves the page again and is still within the lifetime of the cookie, we can identify the user so that it does not have to log on again

/* read cookies to recognize login status/function Checklogin () {if (GetCookie ("music_identify")!= "" && GetCookie ("Music_key_code")!= "") {var id = getcookie ("music_identify"), pass = GetCookie ("Music_ke

        Y_code "), XMLHTTP; if (window.
        XMLHttpRequest) {//code for ie7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest ();
        else {//code for IE6, IE5 xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP");

        } xmlhttp.open ("Get", "pages/loginbycookie.php?user_id=" + ID + "&user_pass=" + Pass, false);
                Xmlhttp.onreadystatechange = function () {if (xmlhttp.readystate = = 4 && xmlhttp.status = 200) {
                    if (xmlhttp.responsetext!= 0) {//do something ...} else {
            Do something ...}
        }
        };
    Xmlhttp.send (); }
}

Read local cookies, send data to server validation via Ajax, and log on after

Then, when the user clicks out of the login or switch account, delete the cookie information saved by the current account, and then refresh the page

/* Exit Login Refresh page, delete cookie status * *
function Exitlogin () {
    document.cookie = "music_identify=";
    Document.cookie = "music_key_code=";
    Window.location.reload (true);

Here, our cookies Save the user login status has been preliminarily implemented!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.