Cookie set with javascript, not recognised with PHP (same domain and path)

These are my cookies:

My cookies

I'm running my website from my own computer using a WAMP server. I access my main page from, and this is the javascript funcion to set the cookies (User and Session):

    function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "; expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + expires;

When I read them using javascript, it works fine. I get my session. Then I go to another PHP page named 'uploader.php' with this code:

    setcookie("TestCookie", "Hello World!", time()+3600);
echo("Session: " . $_COOKIE['Session'] . "<br/>User: " . $_COOKIE['User'] . "<br/>");

And the result is:

Array ( [TestCookie] => Hello World! ) Notice: Undefined index: Session in D:\wamp\www\Zulaijen\uploader.php on line 30 Notice: Undefined index: User in D:\wamp\www\Zulaijen\uploader.php on line 30

Which means my PHP code is not reading the cookies I set with javascript. It only reads the one I set with my PHP code (TestCookie). And I don't understand why. They are within the same domain and the same path.


You should try setting cookie path. Could be that the cookie paths for PHP and JavaScript isn't matching, hence the cookie will not be shared between the two.

JavaScript cookie path: How do I set path while saving a cookie value in JavaScript?

PHP coookie path (see path section):

I finally found out what was causing the problem (by accident). It's very confusing, but it has a very simple solution.

In order to read the cookies from PHP, you must read them from the very beginning of the file.

Doing this:

<?php print_r($_COOKIE); ?>

At the very beginning of the file (before any HTML code) prints every cookie I set correctly as it should. Even if you set them from PHP, if you don't do it from the very beginning of the file you won't be able to get them.

The reason why I was able to read the one I was setting with PHP was simply because I was setting it right before reading it, or so it seems.

Need Your Help

How to check an object is released in firemonkey?

delphi object firemonkey

I create a component and use it at another place,but I don't know if the component was released.

Web Api returns expanded key-value object instead of original JSON object

c# mongodb

When I send {"name":"John Doe", "age":18, "country":"USA"} to my C# Web API with POST to api/test, I store it in my mongo test-collection and return the updated document: