简体   繁体   English

设置Cookies PHP的问题

[英]Issue with Setting Cookies PHP

Right, I've tried everything I can think of and I'm reaching the end of my tether with this! 没错,我已经尽力想尽一切,与此同时,我也将尽一切努力!

Basically I'm trying to set two cookies 'user' and 'usertype'. 基本上,我试图将两个cookie设置为“ user”和“ usertype”。 Now when I set the cookie user to be the actual username usertype gets set as I intend it too. 现在,当我将cookie用户设置为实际用户名时,usertype也将按照我的预期进行设置。

However if I get the cookie 'user' set to the id of the user in the table then for some reason the usertype cookie isn't getting set. 但是,如果我将cookie'user'设置为表中用户的ID,则由于某种原因,未设置usertype cookie。

The code is pretty simple and is: 该代码非常简单,它是:

    setcookie('user',$row['id']);
    setcookie('usertype',$row['type']);
    header('Location:index.php');

This way it doesn't set usertype but does set user correctly, however if I simply change it too: 这样,它不会设置用户类型,但会正确设置用户,但是如果我也简单地更改它的话:

    setcookie('user',$row['username']);
    setcookie('usertype',$row['type']);
    header('Location:index.php');

Then both cookies are set correctly. 然后,两个cookie都正确设置。

Also for reference a var_dump of $row gives: 还可以参考$ row的var_dump给出:

array (size=6)
  'id' => string '2' (length=1)
  'name' => string 'Test User' (length=9)
  'pass' => string '098f6bcd4621d373cade4e832627b4f6' (length=32)
  'username' => string 'test' (length=4)
  'email' => string 'test@test.com' (length=13)
  'type' => string '2' (length=1)

I just don't understand how the first way only sets the user cookie before redirecting to index.php whereas the second way both cookies get set. 我只是不明白第一种方法是如何仅在重定向到index.php之前设置用户cookie,而第二种方法是同时设置两个cookie。 Any help would be greatly appreciated. 任何帮助将不胜感激。

You should really specify the domain when storing cookies: 存储cookie时,您应该真正指定域:

Like this 像这样

setcookie("cookie_name", $value, time() + (60*60*24*30), '/', '.yourdomain.com');

Please, let me know whether it works or not.. 请让我知道它是否有效..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM