开发者

Cookie set with setcookie, but not found with $_COOKIE

I have tried to set a cookie on this page, like this:

<?php
setcookie("fasciaoffer", $name, time()+36000);
?>

I开发者_JAVA技巧 have verified that the cookie is set.

I then want to retrieve the cookie when my customer views their shopping basket and display a message:

<?php
if (isset($_COOKIE["fasciaoffer"]))
   echo "<b>Special offers available</b> - buy any 3 covers & get your 4th     choice   free! " . $_COOKIE["fasciaoffer"] . "!<br />";
else
   echo "<b>Special offers available</b> - none available on current order<br />";
?>

However, the message that comes up in my shopping basket is the one where the cookie has not be found.

What could the problem be? Is my coding correct?


PS. The file which the retrieve bit is in (the shopping basket) is not in the root folder.


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

[..]

path

The path on the server in which the cookie will be available on.

If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

You told us that the file which retrieves the cookie is not in the root path.

If the file that sets it is also not in the root path, be sure to set $path to "/" (or possibly a different value which still fits your use) when you call setcookie.


I've always had an interesting time when working with cookies. But here are my thoughts :

1) Are you sure $name is passing a value? To check this, echo out $name after you place your cookie. I usually test my vars with echo("name : $name
"); just to make sure that my head and PHP are on the same page. If you recieve a null value, there is your problem.

2) I usually find it benefitial to do a page refresh before reading in any cookies. Though you should put a qualifier like if (!isset($_COOKIE['fasciaoffer'])) { set cookie code }

I hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜