How to use cookie

In web application, sometimes, you have to use cookie no matter client cookie or server cookie to store values you want to save. I summarised as below.

Usage 1: Create per cookie per value
Initialize cookie:
HttpCookie cookie = new HttpCookie(“UserName”);
cookie.Value = “admin”;
Response.AppendCookie(cookie );

Retrieve cookie:
HttpCookie cookie = Request.Cookies(“UserName”);
cookieValue = cookie.Value;
Response.AppendCookie(cookie );

If add cookie from server side:
Response.Cookies.Add(new HttpCookie(“UserName”, “admin”)); //add particular cookie into cookie colliections
Retrieve cookie:
cookieValue = Response.Cookies[“UserName”].Value;

Usage 2: Add all values to one cookie object

HttpCookie cookie = Request.Cookies(“Default”);
cookie.Values.Add(“userid”, “1”); || cookie[“userid”] = “1”; //both syntax work
cookie.Values.Add(“username”, “admin”);

HttpCookie cookie = Request.Cookies(“Default”);
cookieValue = cookie.Values[“userid”];

Basic cookie operations: (create, add value, retrieve and delete)

1. js store cookie

<script type="javascript">
function setCookie(name,value){ //name is cookie's name, value is name's value
         var days = 10; //stored days and can passed by parameters
         var expires = new Date(); //create date variable
         expires.setTime(expires.getTime() + days * 30 * 24 * 60 * 60 * 1000); //expires time = current time + expired time (seconds)
         var str = name + '=' + value +';expires=' + expires.toGMTString(); //store value and expire date time to the cookie(need GMT format to display date string)
         var str = name + '=' + escape(value) +’;expires=’ + expires.toGMTString();                  document.cookie = str; }

The following is the generic cookie

<script type="text/javascript" language="JavaScript">//
function addCookie(name,value,expireHours){
           var cookieString=name+"="+escape(value);
           if(expireHours>0){ //check if setup the date time
           var date=new Date(); 
           cookieString=cookieString+"; expire="+date.toGMTString(); 

Notes: Should use escape() function to encode, it could encode special characters to HEX, such as space will compiled to “20%” and able to save into cookie, nevertheless, it could avoid issues in multiple language environment
document.cookie=”str=”+escape(“I love js”);
after encode:
But after encode by escape(), the value needs to revoke unescape()to decode and retrieve the original cookie value

2. js retrieve cookie value

a.general loop characters retrieve

function getCookie(name){
var strcookie = document.cookie;// get cookie string
var arr = strcookie.split(‘;’); //split cookie
for(var i = 0;i&lt;arr.length;i++){
var arrStr = arr.split(‘=’); //split specific cookie
if(arrStr[0] == name) return arrStr[1]; //check if cookie name existing and output
return "";

b.use unescape to get cookie value

function getCookie(name){
var _password = document.getElementById(‘password’);
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); //use regular expression to get cookie to be a name array
return unescape(arr[2]); //
return ”;

3. delete cookie

<script type="text/javascript" language="JavaScript">
function deleteCookie(name){
            var date=new Date();
            document.cookie=name+"=v; expire="+date.toGMTString();  }  

the more details of cookie usage could be referenced by


Leave a Reply

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

You are commenting using your 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