PHP cookies

Hi! I’m trying to create a PHP script but I don’t get it working properly. Here is what I want it to do:

  1. Check if the cookie exists

1.1 If it does, then do nothing - display the page as it normally would
1.2 If it doesn’t, then:

1.2.1 Set a cookie that will auto-delete when visitor leaves the page
1.2.2 Call in a script that does redirect a visitor to the same page

Here’s the code I created but it keeps redirecting no matter what:

<?php

if(isset($HTTP_cookie_VARS['redirected'])){
}else{
setcookie("redirected", "", time()-3600);
require_once("redirect.php");
}

?>

This code IS the first thing that will be loaded and executed. What am I doing wrong?

Thanks, RNEL, but it didn’t help. I set all parameters available but the problem remains.

// OMG! ScallioXTX, Thanks a lot! You just made my day right now! :smiley: It works. Thanks.

So there’s that :slight_smile:

Another thing is that if you don’t specify a value for a cookie it will actually tell the browser to delete the cookie. Why there is no mention of this in Da Manual is beyond me. I’m pretty sure it used to be there, but now it’s not anymore?!

Anyhow, the code you want to use is


setcookie('redirected', true, 0, '/');

:slight_smile:

check also the path on the server in which your cookie will be available on, it is included on the documentation about setcookie() on the link posted above. remember that the default value is the current directory that the cookie is being set in.

Okay, I made a correction, checked the setcookie() $expire parameter, but discovered nothing incorrect in last one. So, now my code looks like this and still same problem - it just keeps redirecting like there is no cookie at all (even if I set the time() to +300 or something so it wouldn’t self-delete).


<?php

if (isset($_COOKIE['redirected'])) {
}else{
setcookie("redirected", "", time()-3600);
require_once("redirect.php");
}

?>

First of all $HTTP_COOKIE_VARS is deprecated, use $_COOKIE instead.

Second of all, look at the documentation for setcookie(), especially the notes on the $expire parameter :slight_smile: