简体   繁体   中英

How to set a cookie for a domain in PHP?

I want to set a cookie via PHP. The scenario is like this:

Domain is: example.com

There is one web page on sub-domain (my.example.com). My code is:

$value="I am looged in";
setcookie("TestCookie", $value,'','',".example.com");
echo "hello".$_COOKIE["TestCookie"];

but the result is only "hello" - the cookie is not getting set.

First two corrections to the actual call of setcookie : Parameter 3 ( expired ) should be an integer value (the default value is 0); parameter four should be set to '/' to make the cookie valid for all subdirectories; the setcookie call should therefore look like this:

setcookie("TestCookie", $value, 0, '/', ".example.com");

Then it should actually work the second time the script is called. To understand why it won't work the first time already, we have to dig in a little into how cookies work ; basically, Cookies are data sent from the server to the client, where the server says "send me this data the next time you send me a request ". That's basically what setcookie is for: When the request is done and the client has received and processed the page, the cookie as specified will have been created at the client; $_COOKIE , on the other hand, holds all values which are in cookies already , and which have been transmitted by the client along with the request - meaning that the first time the script is called, $_SESSION will actually still be empty, since the cookies will only be created once the client has received the scripts output.

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