Search code examples
phpcookiessetcookie

PHP Cookies are not being set


I'm having issues with setting up cookies. The problem is that my cookies aren't even being set, I have setup a test below to see if they are being set but they are never being set. I've even checked in my browser to see if anything is being set, but nothing from my site.

I would like you to help me make my cookies set. I'm not quite sure what to do. Thank you.

Here is my code:

<?php 
session_start();

setcookie("ridArray","", time()+3600);

if (isset($_COOKIE['ridArray'])) {
    echo "ridArray is set.";    
}
?> 
<head>
</head>
<html> 
<body>
<?php
if (isset($_COOKIE['ridArray'])) {
    echo "ridArray is set.";    
} else { echo "not set"; } 
?> 
</body>
</html> 

Solution

  • Here's the problem, from the SetCookie documentation:

    Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to 'deleted' and expiration time to one year in past.

    You are setting the cookie value to empty string (""). Try:

    setcookie("ridArray","not blank value", time()+3600);
    

    The other issue is that when you set a cookie, it will not be in the request headers (accessed via $_COOKIE) until the next page load. This means when you load that page the first time, $_COOKIE['ridArray'] will NOT be set. On subsequent loads, it will be set, and it will be reset every time.

    First page load, it won't be set. Refresh, and it will be set.

    The easiest way to debug cookies is to use something like Chrome's developer tools or Firefox's FireBug and watch the response headers for the SetCookie header, and the request headers to see what cookies your browser is sending.