简体   繁体   English

使用 header(“Set-cookie”) 与 setcookie() 函数设置 cookie

[英]Setting cookie using header(“Set-cookie”) vs setcookie() function

I'm refactoring some code and found something I've never seen.我正在重构一些代码并发现了一些我从未见过的东西。 the function is used for user to set cookie when user logs in:该函数用于用户在登录时设置cookie:

  function setUserCookie($name, $value) {
     $date = date("D, d M Y H:i:s",strtotime('1 January 2015')) . 'GMT';
     header("Set-Cookie: {$name}={$value}; EXPIRES{$date};");
  }

now that I've been assigned to refactor code I'm planning to use setcookie function which essentially does same thing according to php.net.现在我已经被分配到重构代码,我计划使用setcookie函数,它根据 php.net 基本上做同样的事情。

My question is: is there any difference between two and which one should I use?我的问题是:两者之间有什么区别,我应该使用哪一个?

NOTE: this code was written long time ago so I'm assuming that at that time setcookie didnt exist?注意:这段代码是很久以前写的,所以我假设当时setcookie不存在?

There's no good reason not to use setcookie.没有充分的理由不使用 setcookie。 The above code doesn't properly encode names and values, so that's at least one major benefit to refactoring.上面的代码没有正确编码名称和值,所以这至少是重构的一大好处。

The difference between the two functions is that header() is the general function for setting HTTP headers while setcookie() is specifically meant to set the Set-Cookie header.这两个函数的区别在于header()是用于设置 HTTP 标头的通用函数,而setcookie()专门用于设置Set-Cookie标头。

header() therefore takes a string containing the complete header, while setcookie() takes several cookie-specific arguments and then creates the Set-Cookie header from them.因此header()接受一个包含完整头的字符串,而setcookie()接受几个特定于 cookie 的参数,然后从它们创建Set-Cookie头。

Here's a use case in which you can't use setcookie这是一个不能使用 setcookie 的用例

  • you run a website on PHP<7.3你在 PHP<7.3 上运行一个网站
  • you have to set 'SameSite' cookie attribute您必须设置“SameSite”cookie 属性

You can achieve that by exploiting a bug in setcookie, but I wouldn't rely on a bug as it gets fixed over time: setcookie('samesite-test', '1', 0, '/; samesite=strict');您可以通过利用 setcookie 中的错误来实现这一点,但我不会依赖于随着时间的推移而修复的错误: setcookie('samesite-test', '1', 0, '/; samesite=strict');

Or you can use PHP header function: header("Set-Cookie: samesite-test=1; expires=0; path=/; samesite=Strict");或者你可以使用 PHP函数: header("Set-Cookie: samesite-test=1; expires=0; path=/; samesite=Strict");

Note that secure option is required when setting samesite attribute请注意,设置samesite属性时需要安全选项

One big difference is, that setcookie always sets host_only=false and there is nothing you can do about it.一个很大的区别是, setcookie 总是设置 host_only=false 并且你无能为力。

So if you have to set host_only=true for whatever reasons you have to use the header method.因此,如果您出于任何原因必须设置 host_only=true ,则必须使用 header 方法。 As far as I know.我所知道的。

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

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