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?
The Set-Cookie header is sent by the server in response to an HTTP request, which is used to create a cookie on the user's system. The Cookie header is included by the client application with an HTTP request sent to a server, if there is a cookie that has a matching domain and path.
The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers. A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.
php'; function setCookieData($arr) { $cookiedata = getAllCookieData(); if ($cookiedata == null) { $cookiedata = array(); } foreach ($arr as $name => $value) { $cookiedata[$name] = $value; } setcookie('cookiedata', serialize($cookiedata), time() + 30*24*60*60); } function getAllCookieData() { if (isset($_COOKIE[' ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With