Cookie is present in browser, but php $_COOKIE is empty

If there's a cache server or CDN involved, it may be filtering cookies based on a whitelist. This is to improve caching, since each request with a unique set of cookies would need to be regarded as different from other requests and could not be cached (you may receive a different reply from the server based on your cookies, so the cache server cannot serve you the cached response of a previous client). Since lots of services are setting cookies which may be sent to the server (e.g. analytics packages) but have absolutely no influence on the contents of the response, heeding all cookies by default would often completely subvert caching.

Configure the caching server in charge to specifically pay attention to your cookie and to forward it to the origin server. If you have a lot of different cookies, consider giving them a common prefix and whitelist that (e.g. foo-*).


I just dealt with the same issue, my production server was allowing me to create a browser cookie using setcookie('cookieNameHere', $cookieValueHere, time() + (86400 * 365), "/"), but the $_COOKIE variable was always an empty array.

The issue was that my production server blocked direct access to the$_COOKIE variable contents via PHP for security reasons.

My solution was to access the cookie value via JavaScript using the following function:

    function getCookie(cname) {
      var name = cname + "=";
      var decodedCookie = decodeURIComponent(document.cookie);
      var ca = decodedCookie.split(';');
      for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
          c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
          return c.substring(name.length, c.length);
        }
      }
      return "";
    }

I continued to create/update the cookie via PHP.

FYI, I was working on a WordPress site hosted on WP-Engine. See this page for an in depth explanation, and for other options in the event you absolutely need to access a cookie value via PHP (ADMIN-AJAX calls, etc).

Tags:

Php

Cookies