简体   繁体   中英

php cookie not setting on server

I am trying to set a cookie.

I have successfully set it in localhost, but when I tried it on the production site, it doesn't work

localhost code:

 <?php
 if (!$_COOKIE['locationid']){
    setcookie("locationid",'1',time()+604800,'http://localhost/boot/' );
 }
 echo $_COOKIE['locationid']; 

server code:

 <?php
 if (!$_COOKIE['locationid']) {
     setcookie("locationid", '1', time() + 604800, "www.example.com/demo/");
 }
 echo $_COOKIE['locationid']; 

Your call to setcookie doesn't seem right.

It should be something like:

setcookie("locationid", '1', time() + 604800, "/demo/", "example.com");

The third parameter is the path , and you were passing both domain and path together. The fourth parameter is the domain, and you can set it to example.com without the www so it'll work for www and the "naked" domain.

These are all optional parameters, but take notice that setting it this way your cookie will be available when a client hits a page under "/demo/", but not on your site's root ("/").

Also, I would use isset to check for the cookie's existence, like this:

if (isset($_COOKIE['locationid'])) {

The way you are doing it, you are liable to receive a notice for trying to access an undefined index if the cookie is not set.

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