Forum Moderators: coopster

Message Too Old, No Replies

cookie detection

         

xeonaphobe

2:56 pm on Jan 26, 2005 (gmt 0)

10+ Year Member



Was wondering if someone could have a quick look at this code and tell me where i've went wrong;

$canpost = 1;
setcookie("canpost", $canpost, time()+90);

if (!isset($_COOKIE['canpost'])) {
header("Location: index.php");
}

I basically want the user to be redirected to index.php if the user doesn't have cookies enabled. For some reason the above doesn't seem to work. I've been told I could detect this with javascript, but i'd rather avoid that.

Cheers,
Neil

dreamcatcher

2:58 pm on Jan 26, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Change $canpost = 1 from a boolean value to a literal value. All you are saying at the moment is $canpost = true. It has no value when you set the cookie.

Try:

$canpost = "1";

At least I think thats what the problem is.

dc

xeonaphobe

3:40 pm on Jan 26, 2005 (gmt 0)

10+ Year Member



Gave it a try, no luck :(

The problem is definatly here...

if (!isset($_COOKIE['canpost'])) {
header("Location: index.php");
}

At the moment, if a user has cookies disabled, they won't be redirected to index.php. I can't understand why this is happening. Rar...

xeonaphobe

4:14 pm on Jan 26, 2005 (gmt 0)

10+ Year Member



ah problem solved. With the exception of me not declaring $canpost properly, the code was fine. I'd forgotten to clear the cookies that were present before i turned off "accept cookies" when i went to test the thing.

Hate it when i make silly mistakes like that >:-(

Thanks for the help!

dcrombie

12:31 pm on Jan 27, 2005 (gmt 0)



You can do that checking in PHP (at least not on a single page).
The flow is as follows:

1) user requests page (no cookies in Header)
2) the page is parsed on the server using PHP (still no cookie)
3) the server sends the page (as HTML) with a Set-cookie Header
4) the browser receives and sets the cookie as the page is loaded

At this point, the page has been generated and served but the browser has not reported any cookie information to the server so $_COOKIE is empty and the check will always be false (assuming no previous cookies).

5) all future page requests will contain the Cookie information in the Header and your code will work as expected

;)