3

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.

2 Answers2

0

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

Community
  • 1
  • 1
  • Looking at the *My cookies* image though, all the cookies do seem to have the same path: `/Zulaijen` - it's normally *safer* to set it explicitly though, agreed. – CD001 Mar 14 '16 at 15:24
  • I tried setting the path and domain explicitly and it doesn't make any difference. I tried setting it to both the root directory and the Zulaijen directory, and nothing works. I also tried using the JCookie plugin for JQuery and it's the same result. It refuses to be read. – Aarón C de C Mar 14 '16 at 19:39
0

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.