How to save the user name and password to the Cookie? (Html part)

Source: Internet
Author: User
Tags setcookie

On the website, we often see that every time we prepare to log on, the webpage asks us if we want to save the user name and password so that we do not need to enter it again during the next login. How to implement such functions? After two days of research, I finally got a harvest! I will share my experience with you.
The following methods are usually used to record user information on a webpage: Session, Cookie, and ViewState In the. Net environment. In comparison, Session stores user information in the memory. The information will remain valid unless the user closes the webpage. Therefore, the information stored by Session is easy to lose. Cookies are used to save user information to files on the user's machine, so that the information can be saved for a long time. The first two are traditional storage methods, while ViewState is in Microsoft. net environment, it is actually a special Session, but the information is generally stored on the client. For usage of ViewState, you can refer to some materials. I have also described the usage of static variables in Exercise caution Asp.net.
The following uses the user name and password as an example to describe how to save user information through cookies.
Because cookies use files on computers to record related information, the operations on cookies involve reading, assigning, and deleting cookies. In addition, because Cookie provides a validity period function, you can also set a validity period for the Cookie. The following describes how to implement Cookie operations in the DHTML and VS. Net environments.
I. DHTML Environment
In this environment, we use traditional JavaScript scripts to complete our expected tasks by performing operations on the properties and events of various objects on the page.
1. Read the Cookie value
Cookie values are stored by index, that is, different indexes have different cookie values. Therefore, we can index the object we want to store (here it is the user name) and read the cookie value of the stored object. The method is as follows:

function GetCookie (name) { var arg = name + "="; var alen = arg.length; var clen = window.document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (window.document.cookie.substring(i, j) == arg) return getCookieVal (j); i = window.document.cookie.indexOf(" ", i) + 1; if (i == 0)break; } return null;}function getCookieVal (offset){ var endstr = window.document.cookie.indexOf (";", offset); if (endstr == -1)endstr = window.document.cookie.length; return unescape(window.document.cookie.substring(offset, endstr));}

Why are two functions required to read the cookie value? This is because the cookie value is stored in the format of "Cookie name;" + "cookie value;" + "validity period;" + "path. This will be mentioned below. In this way, the first cookie is a series of strings separated by semicolons. We also need to further process it to extract the information we want. In the above two functions, the first function getcookie is used to obtain the location of the cookie we want to read by index, and the second function getcookieval is used to extract the information we want in the cookie. Therefore, you can directly call getcookie (name) when using it. The name is the index of the cookie, that is, the name, or simply something that we want to store its value.
2. Set the cookie value
As mentioned above, the cookie access method is similar to a hash table and uses the name as the index for access. The format of a cookie is as follows:
Cookie name (as a cookie index for future operations) + "=" + cookie value + "; expires = + validity period +"; Path = "+ path +"; domain = "+ domain +"; secure = "+ Security Level
We can see that each cookie actually has six attributes, which exactly constitute a record. Multiple cookies are stored in the hard disk in a set way. That is to say, all cookie records constitute a structure similar to a table. Cookie can have multiple sets. At that time, it cannot be understood as a database? Here we will not explain how to read and write cookie Record Sets in tables or databases, but will explain basic cookie operations. In addition, I have not found any special operation method that treats the cookie set as a table. After all, understanding the cookie set in the form of a table is just a word of my family and is only for your convenience.
Because each cookie is actually composed of multiple attributes, you should set multiple attribute values when setting the cookie. Although not all attributes must be filled in, however, you should at least fill in the cookie name and value. Otherwise, the cookie will be meaningless. You can set a cookie value as follows:

function SetCookie (name, value){ var exp = new Date(); exp.setTime(exp.getTime() + (30*24*60*60*1000));window.document.cookie = name + "=" + escape (value) + "; expires=" + exp.toGMTString()+";path=/";}

Here, name is the cookie name and value is the cookie value. If you want to specify the cookie validity period, you can pass in another time parameter. However, note that the time here is calculated in milliseconds, therefore, if you want to set a day, month, or year for a long period of time, you need to perform the calculation. It should be noted that if the cookie name and value contain Chinese characters, it is best to encode them in advance, otherwise the results may not be very satisfactory.
3. delete a cookie
This may not be appropriate because the following section does not actually Delete cookies. Let's just say that. As mentioned above, each Cookie has a validity period. After the validity period expires, the cookie will become invalid. The obtained cookie value will be null, and the value of this cookie will fail. Therefore, to delete a cookie, you only need to make it expire. Therefore, the operation to delete a cookie is to make it expire:

function DeleteCookie (name){ var exp = new Date(); exp.setTime (exp.getTime() - 100); var cval = GetCookie (name); window.document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString()+";path=/";}

The above Code also shows that the delete operation is to set the validity period of a cookie to the current time minus 1 millisecond, and of course it will expire!
So how can I apply the above Code to the DHTML development process? The following describes how to record the user name and password to Cookie.
For simplicity, we only place a user name text domain, a password domain, a button, and a check box on the page. The page layout code is as follows:

<Html> 

The following describes how to compile the function code. After clicking the "OK" button, the user needs to verify the user name and password and go to the relevant page. Here we will change to the function of recording the user name and password.
Paste the functions of the preceding three cookies Into the

function remember(){if(document.getElementById("remember").checked){SetCookie(document.getElementById("username").value,document.getElementById("password").value);alert("Saved!");}}

In this way, you can record the user name and password to the cookie after clicking the "record" button.
Then, how does one automatically enter the corresponding password after the user enters the user name? Add an event handler in <input id = "username" type = "text">: <input id = "username" type = "text" onblur = "showpassword ()">. Then, place the showpassword () definition between

function showpassword(){  return GetCookie(document.getElementById("username").value);}

The above records the passwords of specific users. Next, we will delete the password. Add an event handler in <input value = "delete" type = "button">: <input value = "delete" type = "button" onclick = "delcookie () ">. Then implement the delcookie () function between

function DelCookie(){DeleteCookie(document.getElementById("username").value);}

Now you can try to see if the expected functions can be implemented. After the test, we will find that after we delete a user's password, every time the focus is removed from username, the password always displays four masks instead of null. Why? If you use the alert () statement to output the content in the text box, you will find that the four masks are actually the word "null. This indicates that the password has been deleted, but this is not ruled out when we show the password. Therefore, you should make a judgment in the showpassword () function. If it is not null, the result will be assigned to the password field:

function showpassword(){ var p=GetCookie(document.getElementById("username").value); if(p!=null)document.getElementById("password").value= p;}

All right, all done. The complete code is as follows:

<Html> 

Below is a simple page counter made by using cookies on the php side.

<?phpsession_start();if(!isset($_COOKIE['kookie'])){$pagecount = 0;setcookie("kookie",$pagecount);echo "<center>This is the firest time you hvae accessed this page in this session.</center>";echo "<center> A cookie was sent to you and stored in your computer.</center>";}else {$pagecount  = ++$_COOKIE['kookie'];setcookie("kookie",$pagecount,time()-10);setcookie("kookie",$pagecount);echo "<center>View Count :<b> ".$_COOKIE['kookie']."</b><center>\n<br>";}?>

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.