Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting cookie using header("Set-cookie") vs setcookie() function

Tags:

php

cookies

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?

like image 801
GGio Avatar asked Jun 06 '13 21:06

GGio


People also ask

What is the difference between set-cookie and cookie header?

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.

What is Setcookie () function?

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.

How set multiple values in cookie in PHP?

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[' ...


2 Answers

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.

like image 128
asmecher Avatar answered Oct 02 '22 15:10

asmecher


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.

like image 41
Sebastian Zartner Avatar answered Oct 02 '22 16:10

Sebastian Zartner