duanchongzi9997 2014-06-06 17:58 采纳率: 0%
浏览 33
已采纳

为什么cookie值错了?

In my login script I calculate a value with md5 and then store that in a database. The id for that row is stored in a cookie on the clients computer. However, the value of the cookie is 1 lower then the actual value. What's causing this?

$cookie = md5($_SERVER['REMOTE_ADDR']+$member['username']+$salt)

$tkn = "INSERT INTO cookies (token) VALUES ('$cookie')";
$tknqry = mysql_query($tkn) or die(mysql_error());
$cookievalue = mysql_insert_id();

setcookie("token", $cookievalue, time()+2678400);   
  • 写回答

2条回答 默认 最新

  • dongyouzhi7218 2014-06-06 18:07
    关注

    Just a guess based off of what you have said in your question. If you use the setcookie() function it does NOT update the $_COOKIE array until a new request is made.

    //cookie has a value of 1 already
    setcookie('token',2);
    
    var_dump($_COOKIE['token'] == 1); //true
    var_dump($_COOKIE['token'] == 2); //false
    

    If you were to refresh the page then the value of $_COOKIE['token'] would equal 2. In your case you probably only want to generate a new one if one isn't set so just check to see if $_COOKIE['token'] is already set:

    if(!isset($_COOKIE['token'])) {
        $cookie = md5($_SERVER['REMOTE_ADDR']+$member['username']+$salt)
    
        $tkn = "INSERT INTO cookies (token) VALUES ('$cookie')";
        $tknqry = mysql_query($tkn) or die(mysql_error());
        $cookievalue = mysql_insert_id();
    
        setcookie("token", $cookievalue, time()+2678400);
    
        //for debug
        echo "cookie set to: $cookievalue";
    } else {
        //for debug
        echo "cookie already set to: {$_COOKIE['token']}";
    }
    

    FYI I would not use mysql_ functions as they are deprecated.

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

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line