Tag Archives: Cookie

Cookies in ASP.NET

Cookies is a small piece of information stored on the client machine. This file is located on client machines “C:\Document and Settings\Currently_Login user\Cookie” path.  Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines. We need to import namespace called  Systen.Web.HttpCookie before we use cookie.
Type of Cookies?

  1. Persist Cookie – A cookie has not have expired time Which is called as Persist Cookie

  2. Non-Persist Cookie – A cookie has expired time Which is called as Non-Persist Cookie

How to create a cookie?
Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie
Example 1:
        HttpCookie userInfo = new HttpCookie(“userInfo”);
        userInfo[“UserName”] = “Annathurai”;
        userInfo[“UserColor”] = “Black”;
        userInfo.Expires.Add(new TimeSpan(0, 1, 0));

Example 2:
        Response.Cookies[“userName”].Value = “Annathurai”;
        Response.Cookies[“userColor”].Value = “Black”;
How to retrieve from cookie?

Its easy way to retrieve cookie value form cookes by help of Request object.
Example 1:
        string User_Name = string.Empty;
        string User_Color = string.Empty;
        User_Name = Request.Cookies[“userName”].Value;
        User_Color = Request.Cookies[“userColor”].Value;

Example 2:
        string User_name = string.Empty;
        string User_color = string.Empty;
        HttpCookie reqCookies = Request.Cookies[“userInfo”];
        if (reqCookies != null)
            User_name = reqCookies[“UserName”].ToString();
            User_color = reqCookies[“UserColor”].ToString();
When we make request from client to web server, the web server process the request and give the lot of information with big pockets  which will have Header information, Metadata, cookies etc., Then repose object can do all the things with browser.

Cookie’s common property:

  1. Domain => Which is used to associate cookies to domain.

  2. Secure  => We can enable secure cookie to set true(HTTPs).

  3. Value    => We can manipulate individual cookie.

  4. Values  => We can manipulate cookies with key/value pair.

  5. Expires => Which is used to set expire date for the cookies.

Advantages of Cookie:

  1. Its clear text so user can able to read it.

  2. We can store user preference information on the client machine.

  3. Its easy way to maintain.

  4. Fast accessing.

Disadvantages of Cookie

  1. If user clear cookie information we can’t get it back.

  2. No security.

  3. Each request will have cookie information with page.

How to clear the cookie information?


  • we can clear cookie information from client machine on cookie folder


  1. To set expires to cookie object
    userInfo.Expires = DateTime.Now.AddHours(1);
    It will clear the cookie with one hour duration.


This article  is copy from http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ some article is very useful, I past it here, so I could use it  when I need it.


Use Cookie to Dynamically Switching Themes

Cookies are little pieces of text that you can store on the user’s computer. The data you store in a cookie is sent only to the server that set it in the first place, so other sites can’t read the cookie from
yours. However, because cookies are stored on the user’s computer as plain text, you should never use them to store any sensitive data, such as a password. Storing harmless data like the preferred
theme is an excellent use of cookies, though.

There has been a lot of debate about cookies and whether or not they can harm your privacy. Generally, cookies are safe, because they only store data that the server that sets it already has. They can’t be used to steal sensitive data from your computer if you haven’t given this data to the server yourself. In most scenarios, cookies improve the user’s browsing experience by remembering little pieces of data instead of asking you every single time you visit a page. Unfortunately, some large corporations like advertising agencies use a unique cookie to track your trails on the web, giving them some global idea of the sites you visit. To ensure that visitors to your site understand what information you have and keep about them, it’s usually a good idea to add a privacy statement to your site describing the intent and usage of cookies and any personal data you may keep.

Use PHP cookie to create a  program that count visitors to this site.

Use PHP cookie to create a  program that count visitors to this site.

here is the source code.

include ‘inc_connect.php’;
if (empty($_COOKIE[“visits”]))
// increment the counter in the database
mysql_query(“UPDATE visit_counter ” .” SET counter = counter + 1 ” .” WHERE id = 1 “);//the expires argument is 1 day to prevent visits from incrementing each time the user returns to the page that contains the site counter
// query the visit_counter table and assign the counter
// value to the $visitors variable
$queryResult = mysql_query(“SELECT counter ” .” FROM visit_counter WHERE id = 1″);
if (($row = mysql_fetch_assoc($queryResult)) !== FALSE)
$visitors = $row[‘counter’];
$visitors = 1;

// Set the cookie value
setcookie(“visits”, $visitors, time()+(60*60*24));
else // Otherwise, assign the cookie value to the $visitor
// variable
$visitors = $_COOKIE[“visits”];

Use PHP cookie to create a program that stores the date and time of a user’s last visit.

Use PHP cookie to create a  program that stores the date and time of a user’s last visit.

here is your source code.

    $lastVisit = “<p>Your last visit was on “.$_COOKIE[‘lastVisit’];
    $lastVisit = “<p>This is your first visit!</p>”;    
setcookie(“lastVisit”, date(“F j, Y, g:i a”),time()+60*60*24*365);

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Untitled Document</title>

<?php echo $lastVisit; ?>

here is the answer cookies login logout info question

first, use javascript the innerHTML create a html_login and log_out page(actional this not a page ,just 2 div),when validate pass then get in show this div info “welcom back use + logout button or a linked paragraph” something like this.

second. ease,you validate the page,for assessment only need validate not empty. For the real world you will go to the database check the info. if not empty, then store the info to document.cookie=txtuser.value + “|” + txtuser.value+’@tafensw.edu’;

third. in you login_div, you just use this info:

here is the code:

var tname=document.getElementById(“txtname”);
    if(tname)tname.value=udata[0];//write into txtname box
    var temail=document.getElementById(“txtemail”);
    if(temail)temail.value=udata[1];//write into txtemail box


Storing the Session ID

PHP uses cookies by default with sessions. If possible, a cookie will be set to store the
session ID.
The other method it can use is adding the session ID to the URL.You can set this to
happen automatically if you set the session.use_trans_sid directive in the php.ini
file. It is off by default.You should use caution when turning this directive on as it
increases your site’s security risks. If this is set to on, a user can email the URL that contains
the session ID to another person, the URL could be stored in a publically accessible
computer, or it may be available in the history or bookmarks of a browser on a publically
accessible computer.

Alternatively, you can manually embed the session ID in links so that it is passed along.The session ID is stored in the constant SID.To pass it along manually, you add it to the end of a link similar to a GET parameter:  <A HREF=”link.php?<?php echo strip_tags(SID); ?>”>
(The strip_tags() function is used here to avoid cross-site scripting attacks.)
Compiling with –enable-trans-sid is generally easier, however.

Setting Cookies from PHP

You can manually set cookies in PHP using the setcookie() function. It has the
following prototype:
bool setcookie (string name [, string value [, int expire [, string path
[, string domain [, int secure]]]]])
The parameters correspond exactly to the ones in the Set-Cookie header mentioned
If you set a cookie as
setcookie (‘mycookie’, ‘value’);

when the user visits the next page in your site (or reloads the current page), you will
have access to the cookie via $_COOKIE[‘mycookie’].
You can delete a cookie by calling setcookie() again with the same cookie name
and an expiry time in the past.You can also set a cookie manually via the header()
function and the cookie syntax given previously. One tip is that cookie headers must be sent before any other headers; otherwise, they will not work. (This is a cookie limitation rather than a PHP limitation.)