Search code examples
phpcookiesphp-7.0

Reading PHP Cookie is Impossible


I tried to read a PHP cookie but I couldn't, although I was able to see it in the Chrome console. I have found the solution myself, using debugging methods, but in case someone else is having the same problem, I'll answer this question myself, in order to save you time.

I was using this code:

if(!empty($_COOKIE['my.cookie'])) {
    echo "cookie value: ".$_COOKIE['my.cookie'];
}
// fallback
else {
    echo "cookie not set!";
}

Solution

  • Using the var_dump() function helped me identify the problem, because the cookie-name was changed by PHP, automatically. (Maybe a bug, or some kind of known limit - my version is PHP 7.0.33.)

    var_dump($_COOKIE);
    

    This resulted in the list of cookies printed on the web page, and the cookie name was changed from "my.page-LANG" to "my_page-LANG".

    So I renamed my cookie and I was good:

    if(!empty($_COOKIE['my_cookie'])) {
        echo "cookie value: ".$_COOKIE['my_cookie'];
    }
    // fallback
    else {
        echo "cookie not set!";
    }