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 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路