duanbi3151 2014-06-14 06:34
浏览 32
已采纳

PHP因为cookie无法正常工作

I am facing some trouble with a conditional statement that uses cookies in PHP.

I would like to change the state of an image based on whether a cookie is set or not. Here is my code (in file MAIN.PHP):

$cookie = "d_content_vote_".$databaseArray['id']; 
if(!isset($_COOKIE[$cookie])) {
  // display image 1 if cookie is not set
}
else { 
  // display image 2 if cookie is set
}

The cookie value (of the timestamp) is set in ../INCLUDES/RATING.PHP, and I make an ajax call to that file. In order to debug, I did a print_r($_COOKIE) in RATING.PHP which gave me this:

Array
(
    [d_content_vote_1] => 1402726678
    [d_content_vote_4] => 1402727148
    [PHPSESSID] => effa8778efbe1b3dfb5bb301e359997d
)

However, when I do a print_r($_COOKIE) in MAIN.PHP I do not get the d_content_vote_* cookies, only the session info.

How do I transfer the cookie that is set in rating.php so that I can use it in main.php. I have never faced this problem before.

[Additional info: I'm building the site on a MAMP server now]

  • 写回答

2条回答 默认 最新

  • douseda0009 2014-06-16 13:20
    关注

    I realised that my cookie was being set and the print_r was done in a file in a subdirectory (/includes) and therefore cannot be used in the root directory. In order to make it work in the root directory, I needed to add another attribute to the function:

    setcookie($name, $value, $time, "/");
    

    The last parameter "/" ensures that the cookie can be used in the root directory.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题