- Setting cookie using header(«Set-cookie») vs setcookie() function
- 5 Answers 5
- HTML Cookies From PHP
- How do you look at the Cookies sent from the browser?
- Lets look at the Cookie header
- Conveniently PHP Puts Cookies In An Associative Array
- How does a server set a Cookie
- Setting the header directly
- How does a server expire a Cookie?
- The cookies for this page as seen on the server
- PHP setcookie() Function
- Definition and Usage
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- Example
- Example
- Example
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:
function setUserCookie($name, $value) < $date = date("D, d M Y H:i:s",strtotime('1 January 2015')) . 'GMT'; header("Set-Cookie: =; EXPIRES;"); >
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?
You might find new Cookie($name) helpful, as found in this standalone library. So that’s a third option for setting cookies. Honestly, never set the HTTP header directly. Use the built-in PHP function or the constructor cited here in order to set cookies with properly escaped values using header values that are built automatically.
5 Answers 5
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.
setcookie() doesn’t pass 2038 on 32-bit systems. It’s an issue for web servers on embedded platforms (they won’t be updated).
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.
Here’s a use case in which you can’t use setcookie
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’);
Or you can use PHP header function: header(«Set-Cookie: samesite-test=1; expires=0; path=/; samesite=Strict»);
Note that secure option is required when setting samesite attribute
One big difference is, that setcookie always sets host_only=false and there is nothing you can do about it.
So if you have to set host_only=true for whatever reasons you have to use the header method. As far as I know.
I replicated what I believe to be the exact behavior of setCookie programmatically. Here is my implementation, if it can be useful for anyone else.
function setUserCookie($name, $value, $expires = 0, $path = "", $domain = "", $secure = false, $http_only = false) < $value = rawurlencode($value); date_default_timezone_set('UTC'); $date = date("D, d-M-Y H:i:s",$expires) . ' GMT'; $header = "Set-Cookie: ="; if($expires != 0) < $header .= "; expires=; Max-Age=".($expires - time()); > if($path != "") < $header .= "; path=".$path; >if($domain != "") < $header .= "; domain=".$domain; >if($secure) < $header .= "; secure"; >if($http_only) < $header .= "; HttpOnly"; >header($header, false); >
The difference with your function are exactly the difference with setCookie (more arguments like custom expires, path, domain, secure and httpOnly). Especially, note the second argument to «header» ( false ) so that it becomes possible to place multiple cookies with different calls to the function.
HTML Cookies From PHP
If you’re looking for a basic introduction that explains what Cookies are, this is not it, try HTML Cookie Introduction. If you’re looking for a tutorial on how to deal with Cookies with javascript, see my tutorial HTML Cookies From Javascript. This short tutorial tells you what’s possible from PHP, and how to accomplish that. It will not explain Cookies, the Set-Cookie header, or tell you what the attributes of a Cookie mean. See HTML Cookie Introduction for that.
How do you look at the Cookies sent from the browser?
Lets look at the Cookie header
You can get a raw look at the Cookies, by looking at the Cookie header that was sent.
They’ll look just like they did in the Cookie header, so you’ll see something like
The cookies that come to you from the browser are ones that you set before. The browser sends them along with a request for the page your PHP code runs in only if the Domain, Path, and Secure attributes match the URL of your page.
Conveniently PHP Puts Cookies In An Associative Array
Instead of dealing with the raw Cookies, we can deal with an array provided for us by PHP. It’s called the $_COOKIE array.
cookie1=$_COOKIE[‘cookie1’]; // value1 cookie2=$_COOKIE[‘user’]; // joe cookie3=$_COOKIE[‘rock’]; // roll
If you weren’t sure if the Cookie was already set, then you’d check first,
How does a server set a Cookie
A server sets a Cookie by sending a Set-Cookie header to the browser. When you are writing code in PHP that sends Cookies, that’s your job. Get a Set-Cookie header sent.
You have to do it before anything else is sent, because as soon as any part of a page is sent, the headers go just before them. After that, it’s too late. The headers already went.
I’m going to show you two ways to send Cookies from PHP. First you can set any headers you want, including a Set-Cookie header. You can just build the header and send it off. Second, PHP has a set of functions just for dealing with Cookies. I’ll show you those second, so you’ll understand better what they are doing, but the thing to remember, is that the only way to set a Cookie is by sending a Set-Cookie header.
Setting the header directly
PHP has a header() method to set a header. Sending a Cookie from PHP can be as simple as
to set a Cookie named user with the value joe
As detailed in HTML Cookie Introduction (and specified in RFC 6265 — HTTP State Management Mechanism, [If you don’t know what an RFC is, see RFCs and a Script to get them]), the date used with a Set-Cookie header is in Greenwich Mean Time (now called UTC). That means that if you send a Set-Cookie header with an Expires attribute, it needs to be in GMT. To set a cookie to expire in a day, you could do this:
// 24 hr * 60 min/hr * 60 sec/min = 86400 sec $thedate=gmdate(‘D, d M Y H:i:s \G\M\T’,$time()+24*60*60);
time() returns the time in seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). We add to that the number of seconds in a day, to get the time for a day from now. We pass that to gmdate along with a format string that gives exactly the format specified in RFC 6265. You can replace the format string with the predefined constant DATE_COOKIE, but oddly, although it produces a date string that can be parsed according to the rules in RFC 6265, it is not exactly the one that the specification says you should use, substituting dashes for spaces between the day, month and year. Both work, but I like to specify the format string as above, so it agrees with the RFC.
That means that from PHP you can do something like
Makes a cookie named acookie with no value
A cookie named acookie with no value but HttpOnly set to true
A cookie named acookie with value 3 that expires a week into the future
How does a server expire a Cookie?
To expire a Cookie, you set the Cookie with the time in the past so that it has already expired. The Cookie should have the same name as it was set with, and in addition should have the same domain, path, and secure attributes as were used to set it. To deal with time drift between machines, it’s safest to use a time a week into the past, but if the times are synchronized, a time one second in the past will delete a Cookie. As an example:
The cookies for this page as seen on the server
Remember, this sets cookies on your machine. The domain will always be the same as the page so that you can set them, and see them. They will always be set to expire when the session is over unless you click the Date in past to delete? button to delete them. The Path is always ‘/’. Secure is never set.
PHP setcookie() Function
The following example creates a cookie named «user» with the value «John Doe». The cookie will expire after 30 days (86400 * 30). The «/» means that the cookie is available in entire website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie «user» (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:
$cookie_name = «user»;
$cookie_value = «John Doe»;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), «/»); // 86400 = 1 day
?>
!DOCTYPE>
if(!isset($_COOKIE[$cookie_name])) echo «Cookie named ‘» . $cookie_name . «‘ is not set!»;
> else echo «Cookie ‘» . $cookie_name . «‘ is set!
«;
echo «Value is: » . $_COOKIE[$cookie_name];
>
?>
Definition and Usage
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. With PHP, you can both create and retrieve cookie values.
The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie was sent with the name «user», a variable is automatically created called $user, containing the cookie value.
Note: The setcookie() function must appear BEFORE the tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
Syntax
Parameter Values
Parameter | Description |
---|---|
name | Required. Specifies the name of the cookie |
value | Optional. Specifies the value of the cookie |
expire | Optional. Specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0 |
path | Optional. Specifies the server path of the cookie. If set to «/», the cookie will be available within the entire domain. If set to «/php/», the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in |
domain | Optional. Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to «example.com». Setting it to www.example.com will make the cookie only available in the www subdomain |
secure | Optional. Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE |
httponly | Optional. If set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages). This setting can help to reduce identity theft through XSS attacks. Default is FALSE |
Technical Details
Return Value: | TRUE on success. FALSE on failure |
---|---|
PHP Version: | 4+ |
PHP Changelog: | PHP 5.5 — A Max-Age attribute was included in the Set-Cookie header sent to the client PHP 5.2 — The httponly parameter was added |
More Examples
Example
Several expire dates for cookies:
// cookie will expire when the browser close
setcookie(«myCookie», $value);
// cookie will expire in 1 hour
setcookie(«myCookie», $value, time() + 3600);
// cookie will expire in 1 hour, and will only be available
// within the php directory + all sub-directories of php
setcookie(«myCookie», $value, time() + 3600, «/php/»);
?>
Example
To modify a cookie, just set (again) the cookie using the setcookie() function:
$cookie_name = «user»;
$cookie_value = «Alex Porter»;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), «/»);
?>
?php
if(!isset($_COOKIE[$cookie_name])) echo «Cookie named ‘» . $cookie_name . «‘ is not set!»;
> else echo «Cookie ‘» . $cookie_name . «‘ is set!
«;
echo «Value is: » . $_COOKIE[$cookie_name];
>
?>
Example
To delete a cookie, use the setcookie() function with an expiration date in the past:
echo «Cookie ‘user’ is deleted.»;
?>
Example
Create a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
if(count($_COOKIE) > 0) echo «Cookies are enabled.»;
> else echo «Cookies are disabled.»;
>
?>