Setting a cookie using a header (Set-cookie function) and setcookie ()

I refactored the code and found something that I had never seen. The function is used to set a cookie by the user when the user logs in:

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

now that I have the refactoring code assigned to me, I plan to use the setcookie function, which essentially does the same thing according to php.net.

My question is: is there a difference between the two and which one should I use?

NOTE: this code was written many years ago, so I assume that setcookie did not exist at that time?

+8
source share
3 answers

There is no reason not to use setcookie. The above code does not correctly encode names and values, so there is at least one important advantage to refactoring.

+4
source

The difference between the two functions is that header() is a common function for setting HTTP headers, and setcookie() designed specifically to set the Set-Cookie header.

header() therefore takes a string containing the full header, and setcookie() takes a few arguments that depend on cookies, and then creates a Set-Cookie header from them.

+2
source

One big difference is that setcookie always sets host_only = false, and there is nothing you can do about it.

Therefore, if for some reason you need to set host_only = true, you should use the header method. As I know.

-one
source

All Articles