Checking if Cookies are Blocked

This is not necessarily true, as demonstrated above.
Can you tell me a browser in which my approach doesn’t work?

I just ran it on my Chrome right now, and get told no cookies for me - even though to the best of my knowledge my browser accepts everything that’s thrown at it.

Chrome Version 42.0.2311.152 m

Checking the version resulted in an update to Chrome.
Chrome Version 43.0.2357.65 m
Does it work any better on that?

Waah! I’m fat. No cookies for me.

Hi fatty Paul,

Thanks for testing.
Which OS are you using?
Are you testing on a server (i.e. not locally)?

1 Like

Ahh nice - running on a server makes things nicely come together.

Om nom nom!

1 Like

Uploaded your test script: [Here] (http://www.johns-jokes.com/downloads/sp-d/testing-cookies/cookie-test.php)

What is the easiest way to view the error console without having to load any scripts?

You can use ctrl+shift+j to view the JavaScript console, but if you want for the purpose of testing, you can replace console.log with window.alert too.

Nice one. Did it work for you?

assuming the worst-case scenario, what’s supposed to happen when cookies are found to be not supported. Is some sort of message to be sent to the server so that an alternate technique can be used instead?

Or would it be better to first advise the user about the issue and recommend that for the best experience that they allow cookies for your site, and if not to then to have the server use other techniques instead?

1 Like

It is always better to make such things invisible to your visitor.

You can get around needing to send a message to the server by testing on the server for whether cookies are blocked first so as to not rely on JavaScript.

Yes, I fully agree. The less JavaScript that is used, the better.

The server could check if a session id exists. If one doesn’t, and also if no steps have been taken yet to supply a session id (there’s none as a GET parameter of the URL) - that’s when the server can tell the user about the cookies policy.

It seems to be much easier from a server, for the constant SID is empty when cookies are used to start a session. When cookies could not be used, SID instead contains a URL parameter with the session id.

I’m no PHP expert, but I’ll put something together to see how easy/hard it is to do things from a server-side point of view.

Yes, no problem.

I modified the script to include the date.

Demo with source code

Okay - the PHP way to deal with sessions regardless of whether cookies are enabled or not.

When starting the session, there are three possible situations that can occur:

  • Best case: the cookies contain the session name, which means that the session was likely to be appropriately set from a session cookie. No more action needed.
  • Alternate case: It’s a user’s first time visiting your site, so the start_session page is revisited. If cookies are supported it becomes a best case situation. Otherwise . . ,
  • Worst case: No session even after a revisit, so cookies aren’t being used. If we still want the session we must place the session identifier in URL from now on.

It can also be useful to know if this is the start of a new session, for which an additional URL parameter is sent, so that you may for example want to show information about cookies when there is no other cookie or user-account information that prevents it from being shown.

Here’s start_session.php to get started with:

start_session.php

<?php
/* Start a session then return back to a defined location.

   Two possible situations can occur here:

   1. If an earlier session_start resulted in a cookie being saved, we don't need to do anything.
   2. If however no cookie was saved, we need to pass the session id (stored in SID) and
      give the user advice about perhaps enabling cookies.
*/

$return = FILTER_INPUT(INPUT_GET, 'return', FILTER_SANITIZE_STRING);
$cookieCheck = FILTER_INPUT(INPUT_GET, 'cookiecheck', FILTER_SANITIZE_STRING);

$hasSessionCookie = !empty($_COOKIE[session_name()]);
$isFirstSession = $hasSessionCookie || !empty($cookieCheck);

session_start();
if ($hasSessionCookie) {
    // We have a session and a cookie - all is right in the world. Nothing more to see here
    header('Location: ' . $return);
    exit;
}

// It might be their first time here, so reload the page and do a cookie check.
if (empty($cookieCheck)) {
    // go around for a second time, to check if session is stored in cookie
    header('Location: ' . $_SERVER['PHP_SELF'] . '?cookiecheck=yes&return=' . $return);
    exit;
}

// No cookies
// The URL parameter is now used to retain session info
// - When using the SID constant, it must always be first in the querystring
header('Location: ' . $return . '?' . SID);
exit;
?>

And here’s how you can use the start_session.php script:

session_start();

// Check if session exists
$session_id = FILTER_INPUT(INPUT_GET, session_name(), FILTER_SANITIZE_STRING);
if (!empty(SID) && empty($session_id)) {
    // Either new session or no cookies
    header('Location: start_session.php?return=' . $_SERVER['PHP_SELF']);
}

A full example as login.php follows:

login.php

<?php
session_start();

// Check if session exists
$session_id = FILTER_INPUT(INPUT_GET, session_name(), FILTER_SANITIZE_STRING);
if (!empty(SID) && empty($session_id)) {
    // Either new session or no cookies
    header('Location: start_session.php?return=' . $_SERVER['PHP_SELF']);
}

function array_unshift_assoc(&$arr, $key, $val) 
{ 
} 

// When cookies are not being used for the session, this adds the session parameter to the start of the URL 
function href($href, $params = []) {
    // If a session parameter is given, it must appear first on the URL
    if (!empty(SID)) {
        // put the session id at the start of the params
        $params = array_reverse($params, true); 
        $params[session_name()] = session_id(); 
        $params = array_reverse($params, true); 
    }
    return $href . ($params ? '?' . http_build_query($params) : '');
}

function pass_session() {
    // Submit the session id as a hidden field of the form
    $session_id = FILTER_INPUT(INPUT_GET, session_name(), FILTER_SANITIZE_STRING);
    if (!empty($session_id)) {
        echo '<input type="hidden" name="' . session_name() . '" value="' . $session_id . '">';
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Check for cookies login</title>
<style type="text/css">
.warning {
    background: pink;
}
</style>
</head>
<body>
<p>Please login to the test service:</p>
<form action="login.php">
<?php pass_session();?>
<p>
    <label for="username">Username</label>
    <input id="username" type="text" name="username" value="">
</p>
<p>
    <label for="password">Password</label>
    <input id="password" type="password" name="password" value="">
</p>
<p><input type="submit" name="submit" value="Login"></p>
</form>
<?php $params = array("return" => $_SERVER['PHP_SELF']); ?>
<p><a href="<?php echo href('kill_session.php', $params);?>">Kill session</a></p>
</body>
</html>

And finally to make testing easier, the Kill session link uses the following to script to reset your session:

kill_session.php

<?php
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

setcookie(session_name(), '', time() - 42000);

$return = FILTER_INPUT(INPUT_GET, 'return', FILTER_SANITIZE_STRING);
if (!empty($return)) {
    header('Location: '. $return); 
}
?>

As a reminder - this is the JavaScript forum and the above is PHP code. There are likely better ways to achieve things on PHP, but the above code is a good starting point from which to work from.

Whew! I finally remembered where there was a websote that did what I think I need…

Go to this website and block cookies and you will see…

http://www.theaustralian.com.au/nocookies

Some day when I learn JavaScript I like this.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.