views:

3498

answers:

7

How to detect on server side that cookies in browser are disabled? Is it possible?

Detailed explanation of question:

I am processing HTTP request on the server. I want to set cookie via Set-Cookie header. I need to know at that time whether cookie will be set by client browser or my request to set cookie will be ignored.

+3  A: 

Try to store something into a cookie, and then read it. If you don't get what you expect, then cookies are probably disabled.

Joonas Pulakka
A lot of websites do this. It's not possible (on the server) to figure out if cookies are enabled on the *first* request, but you can implement a short redirect step to figure it out.
tlianza
+6  A: 

Send a redirect response with the cookie set; when processing the (special) redirected URL test for the cookie - if it's there redirect to normal processing, otherwise redirect to an error state.

Note that this can only tell you the browser permitted the cookie to be set, but not for how long. My FF allows me to force all cookies to "session" mode, unless the site is specifically added to an exception list - such cookies will be discarded when FF shuts down regardless of the server specified expiry. And this is the mode I run FF in always.

Software Monkey
except for stackoverflow?
Simon_Weaver
Except for a number of sites, one of which is indeed SO.
Software Monkey
+1  A: 

You can use javascript code and send an ajax response to the server for that. Usually the detection and re-direction to a non-cookie version takes place in the client.

kgiannakakis
+11  A: 

I dont think there are direct ways to check. The best way is to store a value in the cookie and try to read them and decide whether cookies are enabled or not. Here are some examples for you.

Shoban
+6  A: 

fell free to use Javascript to accomplish that

Library:

<script type="text/javascript">
    function createCookie(name, value, days) {
        var expires;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        else expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    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;
    }

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

    function areCookiesEnabled() {
        var r = false;
        createCookie("testing", "Hello", 1);
        if (readCookie("testing") != null) {
            r = true;
            eraseCookie("testing");
        }
        return r;
    }
</script>

Code to run:

<script type="text/javascript">
    alert(areCookiesEnabled());
</script>

Remember

this only works if Javascript are allowed to run!

balexandre
The question is about how to detect cookies on the server side. Your code runs on the client side.
Adam
Server Side - But he didn't specified what server language he is using! But the trick is the same... write a cookie and see if it's there... if it is, Cookies Enabled, if not... Disabled ;)
balexandre
+1  A: 

The question whether cookies are "enabled" is too boolean. My browser (Opera) has a per-site cookie setting. Furthermore, that setting is not yes/no. The most useful form is in fact "session-only", ignoring the servers' expiry date. If you test it directly after setting, it will be there. Tomorrow, it won't.

Also, since it's a setting you can change, even testing whether cookies do remain only tells you about the setting when you tested. I might have decided to accept that one cookie, manually. If I keep being spammed, I can (and at times, will) just turn off cookies for that site.

MSalters
Good point, but I just need to know if my Set-Cookie header will result in that next request from the same client will came with that cookie or not. It is not important for me if it is permanent or just session-only.
Sasha Yanovets
+2  A: 

A standard way of checking for cookie support is via a redirect.

For reasons I'll explain below, I think it's best to do a cookie check only when the user initiates an action that would require a cookie such as attempting to log in, or adding something to their cart.

First, the server checks the login data as normal - ie if the login data is wrong the user receives that feedback as normal. It immediately responds with a cookie, and a redirect to a page which is designed to check for cookie preferences - which may just be the same URL but with some flag added to the query string. This next page will then check to see if the client sent any cookie. If not, then the user receives a message stating that a cookie was not received and they should probably try to enable cookies if they want to log in.

Now for why I only do a cookie test after a user-initiated action other than simply loading a page. I have seen sites implement a cookie test on every single page, not realising that this is going to have effects on things like search engines trying to crawl the site. That is, if a user has cookies enabled, then the test cookie is set once, so they only have to endure a redirect on the first page they request and from then on there are no redirects. However, for any browser or other user-agent, like a search engine, that doesn't return cookies, every single page could have a redirect. While it'll still work and a lot of the time users won't see any difference, it is a lot more overhead and load than necessary.

Another method of checking for cookie support is with Javascript - this way, no redirect is necessarily needed - you can write a cookie and read it back virtually immediately to see if it was stored and then retrieved. The downside to this is it runs in script - ie if you still want the message about whether cookies are supported to get back to the server, then you still have to organise that - such as with an Ajax call.

For my own application, I implement some protection for 'Login CSRF' attacks, a variant of CSRF attacks, by setting a cookie containing a random token on the login screen before the user logs in, and checking that token when the user submits their login details. Read more about Login CSRF from Google. A side effect of this is that the moment they do log in, I can check for the existence of that cookie - an extra redirect is not necessary.

thomasrutter