文字

Cookie

PHP 透明地支持 HTTP cookie。cookie 是一种在远程浏览器端储存数据并以此来跟踪和识别用户的机制。可以用 setcookie() setrawcookie() 函数来设置 cookie。cookie 是 HTTP 标头的一部分,因此 setcookie() 函数必须在其它信息被输出到浏览器前调用,这和对 header() 函数的限制类似。可以使用输出缓冲函数来延迟脚本的输出,直到按需要设置好了所有的 cookie 或者其它 HTTP 标头。

如果 variables_order 中包括“C”,则任何从客户端发送的 cookie 都会被自动包括进 $_COOKIE 自动全局数组。如果希望对一个 cookie 变量设置多个值,则需在 cookie 的名称后加 [] 符号。

根据 register_globals 的设置,可以从 cookie 建立普通的 PHP 变量。但是不推荐依赖于此特性,因为出于安全原因此选项通常是关闭的。在早期的 PHP 版本中,当 track_vars 配置选项打开时(此选项自 PHP 4.0.3 后总是打开的),系统还会设定 $HTTP_COOKIE_VARS

关于更多细节以及有关浏览器问题的注意事项,参见 setcookie() setrawcookie() 函数。

用户评论:

[#1] Tugrul [2015-03-08 15:17:24]

Setting new cookie
=============================
<?php 
setcookie
("name","value",time()+$int);

?>


Getting Cookie
=============================
<?php 
echo $_COOKIE["your cookie name"];
?>


Updating Cookie
=============================
<?php 
setcookie
("color","red");
echo 
$_COOKIE["color"];


setcookie("color","blue");
echo 
$_COOKIE["color"];

?>


Deleting Cookie
==============================
<?php 
unset($_COOKIE["yourcookie"]);

setcookie("yourcookie","yourvalue",time()-1);

?>


Reference: http://gencbilgin.net/php-cookie-kullanimi.html

[#2] meetyashah at gmail dot com [2013-04-22 11:53:51]

PAGE 1

<?php echo $_COOKIE["first"]; ?>

PAGE 2

<?php if(isset($_COOKIE["first"])) {
        echo 
$_COOKIE["first"];}
        echo 
'<br />';
        if(isset(
$_COOKIE["second"])){
        echo 
$_COOKIE["second"];        }
        echo 
'<br />';
        if(isset(
$_COOKIE["third"])){
        echo 
$_COOKIE["third"];        }
        
?>

[#3] Anonymous [2013-04-20 10:56:50]

Your note is too short. Trying to test the notes system? Save us the trouble of deleting your test, and don't. It works.

[#4] Henry [2009-05-08 07:15:50]

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.

[#5] ingen at stocken.ws [2006-11-19 12:26:17]

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)*.

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.

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.

:: Pseudo example:
:: 
:: [Start of script:]
:: 
:: 1. Get the session ID(s) from cookie
:: 2. If one of the session ID's is still valid (that is, if there's a storage associated with it - in DB, file or whatever)
::  ____2.1. Open the session
:: 3. Generate a new session ID
:: 4. Save the new session ID with the one just used in cookie
:: 5. Register shutdown function
:: 
:: [End of script (shutdown function):]
:: 
:: 1. If script ended prematurely
:: ____1.1. Save session data using the old Session ID
:: 2. Else
:: ____2.1. Save session data using the new Session ID
:: ____2.2. Make sure the old session ID is added to a list of ID's (used for the purpose described below)
:: ____2.3. Trash the old session storage

There's still the possibility of some deviant network sniffer catching the session cookie as it's sent to the client, and using it before the client gets the chance to. Thus, successfully hijacking the session. 

If an old session ID is used, we must assume the session has been hijacked. Then the client could be asked to input his/her password before data is sent back. Now, since we have to assume that only the legitimate user has the password we won't send back any data until a password is sent from one request.

And finally, (as a sidenote) we could obscure the login details (if the client has support for javascript) by catching the form as it is sent, take the current timestamp and add it to the form in a dynamically generated hidden form object, replace the password field with a new password that is the MD5 (or similar) of the timestamp and the real password. On the serverside, the script will take the timestamp, look at the user's real password and make the proper MD5. If they match, good, if not, got him! (This will of course only work when we have a user with a session that's previously logged in, since we know what password (s)he's supposed to have.) If the user credentials are saved as md5(username+password), simply ask for both the username and password, md5 them and then md5 the timestamp and the user cred. 

---

If you need a javascript for md5: http://pajhome.org.uk/crypt/md5/md5src.html

---

* You could use session_set_save_handler and make sure the session ID is generated in the open function. I haven't done that so I can't make any comments on it yet.

[#6] kalla_durga at gmail dot com [2006-02-03 12:10:20]

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:

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).

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.

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.

[#7] bmorency at jbmlogic dot com [2005-10-07 05:14:03]

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:

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).

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.

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.

[#8] mega-squall at caramail dot com [2005-02-23 13:04:10]

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.

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 !

IMPORTANT NOTE : This disables the ability of using the back button if you send the session ID via POST or GET.

[#9] myfirstname at braincell dot cx [2003-09-24 08:47:59]

[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]

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.

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.

Stuart Livings

上一篇: 下一篇: