Cookie设置为javascript,无法识别PHP(相同的域和路径)

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 http://127.0.0.1/Zulaijen/, 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:

if(!isset($_COOKIE['TestCookie']))
    setcookie("TestCookie", "Hello World!", time()+3600);
print_r($_COOKIE);
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): http://php.net/manual/en/function.setcookie.php

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.