Reputation: 1126
<?php
setcookie("name", "abc");
echo $_COOKIE["name"];
?>
When I reload this page, it shows nothing on the screen. Why?
But reload again, abc is shown.
WHY??
Upvotes: 0
Views: 442
Reputation: 219934
Cookies are sent as part of your page's HTTP response so they don't exist until after your response is sent. That's why you have to reload the page to see the value.
Upvotes: 0
Reputation: 180177
When you set a cookie, it is not available until the next page load.
This is very clearly laid out in the documentation, which you should read.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.
and
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
Upvotes: 11