1

I need on each page check if cookies are enabled.And use this code.

<?php
setcookie('COOK_CHK',uniqid(),time()+60*60*24);
if(!isset($_COOKIE['COOK_CHK'])){
    echo"Cookies are disabled!";
    exit;
}
session_start();
?>

However on the first check it gives me false until i don't refresh the page.I include this code in each page so can not redirect every time i load the page as it reduces performance.However i want to use it even if javascript is disabled.Any suggestions?

AlexP
  • 449
  • 2
  • 9
  • 25
  • http://stackoverflow.com/questions/3230133/accessing-cookie-immediately-after-setcookie You should go look here :) – kaldoran Jun 12 '15 at 13:25
  • unfortunately none of these solutions resolve my problem.For example once i set $_cookie['COOK_CHK']=uniqid(); just after setcookie() it see like cookies are always enabled – AlexP Jun 12 '15 at 13:43
  • If you need to check on *every* page you should consider redesigning your system, because there is no great solution. – deceze Jun 12 '15 at 14:19

2 Answers2

2

Can you use javascript? If so, all it takes is a check at the navigator.cookieEnabled variable.

It works in most modern browsers. You can read more about it here: http://www.w3schools.com/jsref/prop_nav_cookieenabled.asp

FBidu
  • 972
  • 9
  • 21
1

It's not possible because Cookies are in the browser, and PHP send them when the page has render, so will be available just in the second page. A possible way to fix this is using javascript. If you really should do it in PHP, for some crazy reason, send all your request to a main controller and save the state using other method, for example, write a var into a file, then redirect and in the next redirections you'll know if the cookies are enabled without needed any other redirection. Example:

$file = 'cookie_fake_'.$userIP;
if( !isset($_COOKIE['COOK_CHK']) && !file_exists($file) ){
    file_put_contents($file, 'dummy');
    setcookie('COOK_CHK',uniqid(),time()+60*60*24);
    header('Location:/');
    exit;
}
if(!isset($_COOKIE['COOK_CHK'])){
    setcookie('COOK_CHK',uniqid(),time()+60*60*24);
    echo"Cookies are disabled!";
    exit;
}

Then you should write something to clean old files every hour or so, of course you can use a cache layer or a database or anything like that instead of writing a file.


Edit: The previous code will be really f** up if the user enables cookies and refresh the page, now I've fixed so it works at the second time it refresh. Not perfect but... You really should do this using javascript.

Cheers.

Franco Risso
  • 1,572
  • 2
  • 13
  • 18