简体   繁体   中英

How to display a cookie value on a php page that was set on another php page

on a php page called 'article.php' i set up a cookie and display it and all works correctly

# www.mywebpage/library/article.php

setcookie("fanclub_articlesvisited", 'test');

echo $_COOKIE['fanclub_articlesvisited']; //displays perfectly after refreshing

on another php page, called 'new.php' i go

# www.mywebpage/library/new.php

if (isset($_COOKIE['fanclub_articlesvisited'])) {
    echo 'found';
} else {
    echo 'not found';
}

but it always echoes 'not found'. I thought cookies is always global?

I even try

print_r($_COOKIE);

and it shows

Array ( )

as if it doesnt even exists?

What's wrong? Thanks

Are www.mywebpage/library/article.php and www.mywebpage/library/new.php the actual URLs you're accessing? I noticed that you didn't provide a path parameter when setting your cookie, so perhaps the problem is caused by you trying to access the cookie from a directory outside of the one where the cookie was set.

Try this instead:

setcookie("fanclub_articlesvisited", 'test', 0, '/');

Explanation:

By default, a cookie will only be sent in pages above the directory from which it was set. So for example, a cookie set at this URL:

http://example.com/some_stuff/foo.php

will be visible here:

http://example.com/some_stuff/bar.php
http://example.com/some_stuff/subdirectory/foo.php

but not here:

http://example.com/other_stuff/foo.php
http://example.com/index.php

The PHP documentation has more information.

test.php

  <?Php
  setcookie("fanclub_articlesvisited", 'test123');
  echo $_COOKIE['fanclub_articlesvisited']; //displays perfectly after refreshing
  ?>  

test2.php

  <?php 
  echo htmlentities($_COOKIE['fanclub_articlesvisited'], ENT_QUOTES, 'UTF-8'); 
  ?>

for me this works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM