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:
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.
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?
There's no good reason not to use 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()
therefore takes a string containing the complete header, while setcookie()
takes several cookie-specific arguments and then creates the Set-Cookie
header from them.
上一篇: RANDOM认为危险?