Php cookie problem

I set a cookie on localhost with the following syntax

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

The problem is that the first time I look at the page generated by the cookie and it shows firebug

 Cookie testCookie added. hello cookie 

But he does not read the meaning. If I refresh the page, the value is read and the error message "

 Cookie testCookie changed. hello cookie 

How can I get a cookie value to read on the first page load?

+4
source share
2 answers

As I stated in my comment, from your description (although rather vague and not very clear), I think the problem may be that you are trying to read a cookie before sending it to the server.

The way cookies work is as follows:

  • You make a request
  • SENDS server server cookie back to client
  • Page loading - A cookie is NOT visible to PHP on this page.
  • Refresh
  • SENDS client client cookie for server
  • The server WILL GET a cookie header, so PHP can read it
  • Page loading - Cookie IS is displayed here.

If you have not tried it, please upgrade again!

Since you want to read it at the same time as setting, just save the value you set and use it. Alternatively (although this has not been verified), you can manually set it in the $_COOKIE .

So something like this:

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

Then you can read it normally. Please note that I would not recommend overriding the value of the automatic superglobal (the same applies to $_REQUEST , $_POST , $_GET , etc.), and instead prompts you to just save the value you set, and use this.


Another approach would be to use a “gateway” form, meaning that you set a cookie on the gateway page, which then continues to redirect to the next page.

For example, let's say that your stream was as follows: login.phpaccount.php . Instead of POST'ing your login form directly to account.php , you have 2 options.

Option 1: POST back to login.php, configure the cookie, and then redirect to account.php . Option 2: you have a gateway, for example logincheck.php , POST, set a cookie, and then redirect to account.php .

This way account.php can always see your cookie.

+10
source

It may or may not be related, but you assign booleans to parameters that expect integers or strings. If you are new to PHP, it is important to carefully read the manual and understand the function signatures. In this case, you should check out 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]]]]]])

In addition, I get a warning when running your code:

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

All Articles