php set cookie issue

南笙酒味 提交于 2019-12-09 00:52:24

问题


I'm setting a cookie on localhost with the following syntax

setcookie("testCookie ", "hello cookie", false, "/", false);

The problem is the first time I visit the page the cookie is created and firebug shows

Cookie testCookie added.  hello cookie

But it does not read the value. If I refresh the page, the value is read and fire bug shows

Cookie testCookie changed.  hello cookie

How can I get the value of the cookie to be read the first time the page is loaded?


回答1:


As I put in my comment, from your description (although fairly vague and not too understandable), I think the issue may be that you're trying to read the cookie before it's sent to the server.

The way a cookie works is as follows:

  1. You make a request
  2. Server SENDS cookie header back to client
  3. Page loads - Cookie is NOT visible to PHP on this page load
  4. Refresh
  5. Client SENDS cookie header to server
  6. Server RECEIVES cookie header thus PHP can read it
  7. Page loads - Cookie IS visible here.

If you haven't tried already, refresh again!

Since you want to read it at the same time you're setting it, just store the value you're setting and use that. Alternatively (although this is untested), you could manually set it in the $_COOKIE array.

So something like this:

setcookie("helloworld", .. );
$_COOKIE['helloworld'] = $value;

Then you can read it normally. Note that I wouldn't really recommend overriding the value of an automatic superglobal (same goes for $_REQUEST, $_POST, $_GET, etc.), and would instead suggest that you just store the value you're setting and use that.


Another approach would be to use a form of "gateway", meaning you'd set the cookie on a gateway page, which will then continue to redirect you to the next page.

For example, say your flow was as follows: login.php -> account.php. Rather than POST'ing your login form straight to account.php you have 2 options.

Opt 1: POST back to login.php, set the cookie, and then redirect to account.php. Opt 2: Have a gateway, such as logincheck.php, POST through to that, set the cookie, and then redirect to account.php.

This way, account.php can always see your cookie.




回答2:


It may be related or not, but you are assigning boolean values to parameters that expect integers or strings. If you are new to PHP, it's very important that you read the manual carefully and understand function signatures. In this case you have to check http://php.net/setcookie where you can read this:

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

Also, I'm getting a warning when I run your code:

Warning: Cookie names cannot contain any of the following '=,; \t\r\n\013\014'


来源:https://stackoverflow.com/questions/5936054/php-set-cookie-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!