EzDevInfo.com

cookies interview questions

Top cookies frequently asked interview questions

Can an AJAX response set a cookie?

Can an AJAX response set a cookie? If not, what is my alternative solution? Should I set it with Javascript or something similar?


Source: (StackOverflow)

javascript - delete cookie

Is my function of creating cookie correct? and how do i delete cookie at the beginning of my program run? is there a simple coding?

function createCookie(name,value,days)

<script>
    function setCookie(c_name,value,1) {
    document.cookie = c_name + "=" +escape(value);
    }

    setCookie('cookie_name',mac);
</script>


function eraseCookie(c_name) {
    createCookie(cookie_name,"",-1);
}

Source: (StackOverflow)

Advertisements

What is the difference between localStorage, sessionStorage, session and cookies?

What are the technical pros and cons of localStorage, sessionStorage, session and cookies, and when would I use one over the other?


Source: (StackOverflow)

Why is jquery's .ajax() method not sending my session cookie?

After logging in via $.ajax() to a site, I am trying to send a second $.ajax() request to that site - but when I check the headers sent using FireBug, there is no session cookie being included in the request.

What am I doing wrong?


Source: (StackOverflow)

Shortest function for reading a cookie in JavaScript

What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?

Very often, while building stand-alone scripts (where I can't have any outside dependencies), I find myself adding a function for reading cookies, and usually fall-back on the QuirksMode.org readCookie() method (280 bytes, 216 minified.)

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

It does the job, but its ugly, and adds quite a bit of bloat each time.

The method that jQuery.cookie uses something like this (modified, 165 bytes, 125 minified):

function read_cookie(key)
{
    var result;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}

Note this is not a 'Code Golf' competition: I'm legitimately interested in reducing the size of my readCookie function, and in ensuring the solution I have is valid.


Source: (StackOverflow)

How to use Python to login to a webpage and retrieve cookies for later usage?

I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response header and store them so I can use them in the request to download the webpage /data.php.

How would I do this in python (preferably 2.6)? If possible I only want to use builtin modules.


Source: (StackOverflow)

How do you remove a Cookie in a Java Servlet

How do you remove a cookie in a Java servlet?

I tried this: http://www.jguru.com/faq/view.jsp?EID=42225

EDIT: The following now works successfully it appears to be the combination of:

response.setContentType("text/html");

and

cookie.setMaxAge(0);

Before I was doing:

//remove single signon cookie if it hasn't been validated yet
response.setContentType("text/html");
Cookie cookie = new Cookie(SSORealm.SSO_COOKIE_NAME, "");
cookie.setDomain(SSORealm.SSO_DOMAIN);
cookie.setMaxAge(-1);
cookie.setPath("/");
cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
response.addCookie(cookie);

Which expires the cookie when the browser is closed as per the documentation.

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

The full working snippet to expire a cookie is:

//remove single signon cookie if it hasn't been validated yet
response.setContentType("text/html");
Cookie cookie = new Cookie(SSORealm.SSO_COOKIE_NAME, "");
cookie.setDomain(SSORealm.SSO_DOMAIN);
cookie.setMaxAge(0);
cookie.setPath("/");
cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
response.addCookie(cookie);

Source: (StackOverflow)

How do I make an http request using cookies on Android?

I'd like to make an http request to a remote server while properly handling cookies (eg. storing cookies sent by the server, and sending those cookies when I make subsequent requests). It'd be nice to preserve any and all cookies, but really the only one I care about is the session cookie.

With java.net, it appears that the preferred way to do this is using java.net.CookieHandler (abstract base class) and java.net.CookieManager (concrete implementation). Android has java.net.CookieHandler, but it does not seem to have java.net.CookieManager.

I could code it all by hand by inspecting http headers, but it seems like there must be an easier way.

What is the proper way to make http requests on Android while preserving cookies?


Source: (StackOverflow)

Cookies on localhost with explicit domain

I must be missing some basic thing about cookies. On localhost, when I set a cookie on server side and specify the domain explicitly as localhost (or .localhost). the cookie does not seem to be accepted by some browsers.

Firefox 3.5: I checked the HTTP request in Firebug. What I see is:

Set-Cookie:
    name=value;
    domain=localhost;
    expires=Thu, 16-Jul-2009 21:25:05 GMT;
    path=/

or (when I set the domain to .localhost):

Set-Cookie:
    name=value;
    domain=.localhost;
    expires=Thu, 16-Jul-2009 21:25:05 GMT;
    path=/

In either case, the cookie is not stored.

IE8: I did not use any extra tool, but the cookie does not seem to be stored as well, because it’s not being sent back in subsequent requests.

Opera 9.64: Both localhost and .localhost work, but when I check the list of cookies in Preferences, the domain is set to localhost.local even though it’s listed under localhost (in the list grouping).

Safari 4: Both localhost and .localhost work, but they are always listed as .localhost in Preferences. On the other hand, a cookie without an explicit domain, it being shown as just localhost (no dot).

What is the problem with localhost? Because of such a number of incostencies, there must be some special rules involving localhost. Also, it’s not completely clear to me why domains must be prefixed by a dot? RFC 2109 explicitly states that:

The value for the Domain attribute contains no embedded dots or does not start with a dot.

Why? The document indicates it has to do something with security. I have to admit that I have not read the entire specification (may do it latet), but it sounds a bit strange. Based on this, setting cookies on localhost would be impossible.


Source: (StackOverflow)

Using CookieContainer with WebClient class

I've previously used a CookieContainer with HttpWebRequest and HttpWebResponse sessions, but now, I want to use it with a WebClient. As far as I understand, there is no built-in method like there is for HttpWebRequests (request.CookieContainer). How can I collect cookies from a WebClient in a CookieContainer?

I googled for this and found the following sample:

public class CookieAwareWebClient : WebClient
{
    private readonly CookieContainer m_container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        HttpWebRequest webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = m_container;
        }
        return request;
    }
}

Is this the best way to do it?


Source: (StackOverflow)

Is there a setting on Google Analytics to suppress use of cookies for users who have not yet given consent

According to EU Article 5(3) of the E-Privacy Directive (a.k.a 'The Cookie Laws'), web sites that target EU users have to gain opt-in consent from users before they set a cookie.

See ICO Guidance

I am trying to square this with Google Analytics on my web site.

I would imagine that Google Analytics (GA) can do a certain level of analytic data gathering without requiring the use of cookies.

However, I cannot find any info on this (on the Google sites/settings panels) about how to relay information about the 'state of consent' back to Google during a page request. So, my only option seems to be that I should not embed Google tag code at all if the user has not explicitly given consent. Which seems a bit drastic.

Letting my serverside script set a hasConsentedToCookies=FALSE flag in the JavaScript tags would allow me to instruct Google's services to run in a gracefully degraded fashion.

Is there a setting on Google Analytics to suppress use of cookies for users that have not yet given consent?

If so, where can I find info on this?


Source: (StackOverflow)

create, read, and erase cookies with jQuery [duplicate]

Possible Duplicate:
How to set/unset cookie with jQuery?

some body help me. how to create, read, and erase some cookies with jquery


Source: (StackOverflow)

How do HttpOnly cookies work with AJAX requests?

JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site?

Edit: Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option?

Edit 2: Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of HttpOnly?

Edit 3: Here is a quote from Wikipedia:

When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The HttpOnly flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33].

I understand that document.cookie is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only?

In your example, I cannot write to your document.cookie, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.

<script type="text/javascript">
    var req = null;
    try { req = new XMLHttpRequest(); } catch(e) {}
    if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
    if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
    req.open('GET', 'http://stackoverflow.com/', false);
    req.send(null);
    alert(req.getAllResponseHeaders());
</script>

Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...

Final Edit: Ahh, apparently both sites are wrong, this is actually a bug in FireFox. IE6 & 7 are actually the only browsers that currently fully support HttpOnly.

To reiterate everything I've learned:

  • HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers)
  • HttpOnly removes cookie information from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7.
  • XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies.

edit: This information is likely no longer up to date.


Source: (StackOverflow)

Set cookie and get cookie with JavaScript [duplicate]

This question already has an answer here:

I'm trying to set a cookie depending on which css file i choose in my Html. I have a form with a list of options, and different css files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your html file, it should be the previous file you've chosen.

JavaScript code:

function cssLayout() {
    document.getElementById("css").href = this.value;
}


function setCookie(){
    var date = new Date("Februari 10, 2013");
    var dateString = date.toGMTString();
    var cookieString = "Css=document.getElementById("css").href" + dateString;
    document.cookie = cookieString;
}

function getCookie(){
    alert(document.cookie);
}

HTML code:

<form>
    Select your css layout:<br>
    <select id="myList">
        <option value="style-1.css">CSS1</option>
        <option value="style-2.css">CSS2</option>  
        <option value="style-3.css">CSS3</option>
        <option value="style-4.css">CSS4</option>
    </select>
</form>

Source: (StackOverflow)

How do browser cookie domains work?

Due to weird domain/subdomain cookie issues that I'm getting, I'd like to know how browsers handle cookies. If they do it in different ways, it would also be nice to know the differences.

In other words - when a browser receives a cookie, that cookie MAY have a domain and a path attached to it. Or not, in which case the browser probably substitutes some defaults for them. Question 1: what are they?

Later, when the browser is about to make a request, it checks its cookies and filters out the ones it should send for that request. It does so by matching them against the requests path and domain. Question 2: what are the matching rules?


Added:

The reason I'm asking this is because I'm interested in some edge cases. Like:

  • Will a cookie for .example.com be available for www.example.com?
  • Will a cookie for .example.com be available for example.com?
  • Will a cookie for example.com be available for www.example.com?
  • Will a cookie for example.com be available for anotherexample.com?
  • Will www.example.com be able to set cookie for example.com?
  • Will www.example.com be able to set cookie for www2.example.com?
  • Will www.example.com be able to set cookie for .com?
  • Etc.

Added 2:

Also, could someone suggest how I should set a cookie so that:

  • It can be set by either www.example.com or example.com;
  • It is accessible by both www.example.com and example.com.

Source: (StackOverflow)