manual/en/features.cookies.php

20190523_rev01 · COMPARED WITH 20190101_rev01 · ARCHIVE SNAPSHOT, DATE APPROXIMATE

Full text changes — 20190101_rev01 to 20190523_rev01

1PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the [setcookie()](http://php.net/manual/en/function.setcookie.php) or [setrawcookie()](http://php.net/manual/en/function.setrawcookie.php) function. Cookies are part of the HTTP header, so [setcookie()](http://php.net/manual/en/function.setcookie.php) must be called before any output is sent to the browser. This is the same limitation that [header()](http://php.net/manual/en/function.header.php) has. You can use the [output buffering functions](http://php.net/manual/en/ref.outcontrol.php) to delay the script output until you have decided whether or not to set any cookies or send any headers.
1PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the [setcookie()](https://www.php.net/manual/en/function.setcookie.php) or [setrawcookie()](https://www.php.net/manual/en/function.setrawcookie.php) function. Cookies are part of the HTTP header, so [setcookie()](https://www.php.net/manual/en/function.setcookie.php) must be called before any output is sent to the browser. This is the same limitation that [header()](https://www.php.net/manual/en/function.header.php) has. You can use the [output buffering functions](https://www.php.net/manual/en/ref.outcontrol.php) to delay the script output until you have decided whether or not to set any cookies or send any headers.
22
3Any cookies sent to server from the client will automatically be included into a [$\_COOKIE](http://php.net/manual/en/reserved.variables.cookies.php) auto-global array if [variables\_order](http://php.net/manual/en/ini.core.php) contains "C". If you wish to assign multiple values to a single cookie, just add _\[\]_ to the cookie name.
3Any cookies sent to server from the client will automatically be included into a [$\_COOKIE](https://www.php.net/manual/en/reserved.variables.cookies.php) auto-global array if [variables\_order](https://www.php.net/manual/en/ini.core.php) contains "C". If you wish to assign multiple values to a single cookie, just add _\[\]_ to the cookie name.
44
5On older PHP systems (5.3 or earlier), [register\_globals](http://php.net/manual/en/ini.core.php) may be enabled, which may cause undesirable and insecure operation. If this is enabled, cookies will be registered as global variables.
5On older PHP systems (5.3 or earlier), [register\_globals](https://www.php.net/manual/en/ini.core.php) may be enabled, which may cause undesirable and insecure operation. If this is enabled, cookies will be registered as global variables.
66
7For more details, including notes on browser bugs, see the [setcookie()](http://php.net/manual/en/function.setcookie.php) and [setrawcookie()](http://php.net/manual/en/function.setrawcookie.php) function.
7For more details, including notes on browser bugs, see the [setcookie()](https://www.php.net/manual/en/function.setcookie.php) and [setrawcookie()](https://www.php.net/manual/en/function.setrawcookie.php) function.
88
9177
9183
1010
11[**_Tugrul_**](http://php.net/manual/en/features.cookies.php) [¶](http://php.net/manual/en/features.cookies.php)
11[**_Tugrul_**](https://www.php.net/manual/en/features.cookies.php) [¶](https://www.php.net/manual/en/features.cookies.php)
1212
13**3 years ago**
13**4 years ago**
1414
1515`Setting new cookie ============================= <?php setcookie("name","value",time()+$int); /*name is your cookie's name value is cookie's value $int is time of cookie expires*/ ?> Getting Cookie ============================= <?php echo $_COOKIE["your cookie name"]; ?> Updating Cookie ============================= <?php setcookie("color","red"); echo $_COOKIE["color"]; /*color is red*/ /* your codes and functions*/ setcookie("color","blue"); echo $_COOKIE["color"]; /*new color is blue*/ ?> Deleting Cookie ============================== <?php unset($_COOKIE["yourcookie"]); /*Or*/ setcookie("yourcookie","yourvalue",time()-1); /*it expired so it's deleted*/ ?> Reference: [http://gencbilgin.net/php-cookie-kullanimi.html](http://gencbilgin.net/php-cookie-kullanimi.html)`
1616
171
178
1818
19[**_costamilam073 at gmail dot com_**](http://php.net/manual/en/features.cookies.php) [¶](http://php.net/manual/en/features.cookies.php)
19[**_myfirstname at braincell dot cx_**](https://www.php.net/manual/en/features.cookies.php) [¶](https://www.php.net/manual/en/features.cookies.php)
2020
21**3 months ago**
21**15 years ago**
2222
23`[Editor's note: Wilson's comment has been deleted since it didn't contain much useful information, but this note is preserved although its reference is lost]`
24
25`Just a general comment on Wilton's code snippet: It's generally considered very bad practice to store usernames and/or passwords in cookies, whether or not they're obsfucated. Many spyware programs make a point of stealing cookie contents.`
26
27`A much better solution would be to either use the PHP built in session handler or create something similar using your own cookie-based session ID. This session ID could be tied to the source IP address or can be timed out as required but since the ID can be expired separately from the authentication criteria the authentication itself is not compromised.`
28
29`Stuart Livings`
30
31\-9
32
33[**_costamilam073 at gmail dot com_**](https://www.php.net/manual/en/features.cookies.php) [¶](https://www.php.net/manual/en/features.cookies.php)
34
35**8 months ago**
36
2337`Isso:`
2438
2539`<?php unset($_COOKIE["cookie"]); ?> Apenas apaga um índice de uma variável, os cookies ainda vão existir e continuar a ser enviados do servidor pro cliente e vice-versa. Assim como isso:`
2640
2741`<?php $_COOKIE["cookie"] = "foo bar"; ?> Não cria ou altera o valor do cookie, apenas durante a execução atual, o valor que será passado do servidor pro cliente e vice-versa será o original`
2842
2943`Para excluir ou alterar deve SEMPRE sobre escrever o valor antigo com setcookie(), setrawcookie() ou header(), sendo este último não muito comum e dificilmente terá um uso justificável`
3044
3115
45\-36
3246
33[**_myfirstname at braincell dot cx_**](http://php.net/manual/en/features.cookies.php) [¶](http://php.net/manual/en/features.cookies.php)
47[**_bmorency at jbmlogic dot com_**](https://www.php.net/manual/en/features.cookies.php) [¶](https://www.php.net/manual/en/features.cookies.php)
3448
35**15 years ago**
49**13 years ago**
3650
37`[Editor's note: Wilson's comment has been deleted since it didn't contain much useful information, but this note is preserved although its reference is lost]`
51`In response to the solution posted in the comment below, there are some practical issues with this solution that must be kept in mind and handled by your code. I developed an application using a similar "use-it-once" key to manage sessions and it worked great but we got some complaints about legitimate users getting logged out without reasons. Turns out the problem was not tentative highjacking, it was either:`
3852
39`Just a general comment on Wilton's code snippet: It's generally considered very bad practice to store usernames and/or passwords in cookies, whether or not they're obsfucated. Many spyware programs make a point of stealing cookie contents.`
53`A- Users double click on links or make 2 clicks very fast. The same key is sent for the 2 clicks because the new key from the first click didn't get to the browser on time for the second one but the session on the server did trash the key for the new one. Thus, the second click causes a termination of the session. (install the LiveHttpHeaders extension on firefox and look at the headers sent when you click twice very fast, you'll see the same cookie sent on both and the new cookie getting back from the server too late).`
4054
41`A much better solution would be to either use the PHP built in session handler or create something similar using your own cookie-based session ID. This session ID could be tied to the source IP address or can be timed out as required but since the ID can be expired separately from the authentication criteria the authentication itself is not compromised.`
55`B- For any given reason, the server experiences a slow down and the response with the new key (which has replaced the old one on the server) is not returned to the browser fast enough. The user gets tired of waiting and clicks somewhere else. He gets logged out because this second click send the old key which won't match the one you have on your server.`
4256
43`Stuart Livings`
57`Our solution was to set up a grace period where the old key was still valid (the current key and the previous key were both kept at all times, we used 15 seconds as a grace period where the old key could still be used). This has the drawback of increasing the window of time for a person to highjack the session but if you tie the validity of the old key to an IP address and/or user agent string, you still get pretty good session security with very very few undesired session termination.`
4458
45\-36
59\-46
4660
47[**_bmorency at jbmlogic dot com_**](http://php.net/manual/en/features.cookies.php) [¶](http://php.net/manual/en/features.cookies.php)
61[**_kalla\_durga at gmail dot com_**](https://www.php.net/manual/en/features.cookies.php) [¶](https://www.php.net/manual/en/features.cookies.php)
4862
4963**13 years ago**
5064
5165`In response to the solution posted in the comment below, there are some practical issues with this solution that must be kept in mind and handled by your code. I developed an application using a similar "use-it-once" key to manage sessions and it worked great but we got some complaints about legitimate users getting logged out without reasons. Turns out the problem was not tentative highjacking, it was either:`
5266
5367`A- Users double click on links or make 2 clicks very fast. The same key is sent for the 2 clicks because the new key from the first click didn't get to the browser on time for the second one but the session on the server did trash the key for the new one. Thus, the second click causes a termination of the session. (install the LiveHttpHeaders extension on firefox and look at the headers sent when you click twice very fast, you'll see the same cookie sent on both and the new cookie getting back from the server too late).`
5468
5569`B- For any given reason, the server experiences a slow down and the response with the new key (which has replaced the old one on the server) is not returned to the browser fast enough. The user gets tired of waiting and clicks somewhere else. He gets logged out because this second click send the old key which won't match the one you have on your server.`
5670
5771`Our solution was to set up a grace period where the old key was still valid (the current key and the previous key were both kept at all times, we used 15 seconds as a grace period where the old key could still be used). This has the drawback of increasing the window of time for a person to highjack the session but if you tie the validity of the old key to an IP address and/or user agent string, you still get pretty good session security with very very few undesired session termination.`
5872
59\-49
73\-56
6074
61[**_Henry_**](http://php.net/manual/en/features.cookies.php) [¶](http://php.net/manual/en/features.cookies.php)
75[**_Henry_**](https://www.php.net/manual/en/features.cookies.php) [¶](https://www.php.net/manual/en/features.cookies.php)
6276
63**9 years ago**
77**10 years ago**
6478
6579`It is better to note not to attach your cookies to and IP and block the IP if it is different as some people use Portable Browsers which will remember the cookies. It is better to show a login screen instead if the IP does not correspond to the session cookie's IP.`
6680
67\-39
81\-47
6882
69[**_mega-squall at caramail dot com_**](http://php.net/manual/en/features.cookies.php) [¶](http://php.net/manual/en/features.cookies.php)
83[**_mega-squall at caramail dot com_**](https://www.php.net/manual/en/features.cookies.php) [¶](https://www.php.net/manual/en/features.cookies.php)
7084
71**13 years ago**
85**14 years ago**
7286
7387`I found a solution for protecting session ID without tying them to client's IP. Each session ID gives access for only ONE querry. On the next querry, another session ID is generated and stored. If somebody hacks the cookie (or the session ID), the first one of the user and the pirate that will use the cookie will get the second disconnected, because the session ID has been used.`
7488
7589`If the user gets disconnected, he will reconnect : as my policy is not to have more than one session ID for each user (sessions entries have a UNIQUE key on the collomn in which is stored user login), every entries for that user gets wiped, a new session ID is generated and stored on users dirve : the pirate gets disconnected. This lets the pirate usually just a few seconds to act. The slower visitors are browsing, the longer is the time pirates get for hacking. Also, if users forget to explicitly end their sessions .... some of my users set timeout longer than 20 minutes !`
7690
7791`IMPORTANT NOTE : This disables the ability of using the back button if you send the session ID via POST or GET.`
7892
79\-44
93\-61
8094
81[**_kalla\_durga at gmail dot com_**](http://php.net/manual/en/features.cookies.php) [¶](http://php.net/manual/en/features.cookies.php)
95[**_ingen at stocken.ws_**](https://www.php.net/manual/en/features.cookies.php) [¶](https://www.php.net/manual/en/features.cookies.php)
8296
8397**12 years ago**
8498
85`In response to the solution posted in the comment below, there are some practical issues with this solution that must be kept in mind and handled by your code. I developed an application using a similar "use-it-once" key to manage sessions and it worked great but we got some complaints about legitimate users getting logged out without reasons. Turns out the problem was not tentative highjacking, it was either:`
86
87`A- Users double click on links or make 2 clicks very fast. The same key is sent for the 2 clicks because the new key from the first click didn't get to the browser on time for the second one but the session on the server did trash the key for the new one. Thus, the second click causes a termination of the session. (install the LiveHttpHeaders extension on firefox and look at the headers sent when you click twice very fast, you'll see the same cookie sent on both and the new cookie getting back from the server too late).`
88
89`B- For any given reason, the server experiences a slow down and the response with the new key (which has replaced the old one on the server) is not returned to the browser fast enough. The user gets tired of waiting and clicks somewhere else. He gets logged out because this second click send the old key which won't match the one you have on your server.`
90
91`Our solution was to set up a grace period where the old key was still valid (the current key and the previous key were both kept at all times, we used 15 seconds as a grace period where the old key could still be used). This has the drawback of increasing the window of time for a person to highjack the session but if you tie the validity of the old key to an IP address and/or user agent string, you still get pretty good session security with very very few undesired session termination.`
92
93\-59
94
95[**_ingen at stocken.ws_**](http://php.net/manual/en/features.cookies.php) [¶](http://php.net/manual/en/features.cookies.php)
96
97**12 years ago**
98
9999`If you want a secured session not tied to the client IP you can use the valid-for-one-query method below, but to safeguard against a scenario where the legitimate user clicks twice, you can use a shutdown function (register_shutdown_function)*.`
100100
101101`It will check to see if the script terminated prematurely (connection_aborted), and reset the valid session ID. That way, it's still valid when the user makes the second request. If the script ends properly, the new session ID will be used instead.`
102102
103103`Now, since you can't set a cookie from the shutdown function (after output has been sent), the cookie should contain both the previous valid session ID and the new one. Then the server script will determine (on the next request) which one to use.`
104104