Cookie的理解

1》cookie詳解


什麼是cookie

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. The browser may store it and send it back with the next request to the same server. Typically, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.

     cookie(“小甜餅”)就是服務器發送到我們web瀏覽器的一小塊數據。瀏覽器會存儲它並且當下次再訪問同一個網站,web服務器會先看看它上次有沒有他上次留下的cookies資料,有的話會依據cookie裏的內容來判斷使用者,送出特定的網頁內容給你。


cookie的三大作用

-Session management
     logins,shopping carts,game scores,or anything else the server should remember

-Personalization(個性化設置)
     User preferences,themes,and other settings

-Tracking
     Recording and analyzing user behavior


Create Cookies (創建cookie)

When receiving an HTTP request, a server can send a Set-Cookie header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header. An expiration date or duration can be specified, after which the cookie is no longer sent. Additionally, restrictions to a specific domain and path can be set, limiting where the cookie is sent.

    當服務器接收到一個http請求時會發送一個Set-Cookie的響應頭,這cookie通常會被瀏覽器存儲,並且這cookie會被寫在訪問同一個服務器的http請求頭中。此外,我們使用了cookie的一些屬性來限定cookie的使用。例如Domain屬性能夠在瀏覽器端對cookie發送進行限定;Expires屬性則指定了該Cookie保存的時間限制;屬性Path,則用來指定Cookie將被髮送到服務器的哪一個目錄路徑下。

The Set-Cookie and Cookie headers

Set-Cookie 的響應頭會從服務器端發送cookie到瀏覽器端。

HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry

[page content]

現在每個新的請求,瀏覽器會利用cookie 頭把所有先前存儲的cookies發送到服務器。

GET /sample_page.html HTTP/1.1
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry

Session cookie

上面的cookie是一個session cookie:當客戶端關閉時它會被刪除。因爲它沒有指定Expires或Max-Age指令。但是,Web瀏覽器可能會使用會話還原,這會使大多數會話cookie永久保留,就像瀏覽器從未關閉一樣。

Permanent cookie

永久cookie只會在特定的時間過期而不是在客戶端關閉時過期

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;

Secure and HttpOnly cookies

安全cookie僅通過HTTPS協議通過加密請求發送到服務器。但是儘管安全,重要的東西還是不能放在cookie中。爲了防止跨站點腳本(XSS)***,JavaScript的Document.cookie API無法訪問HttpOnly cookie;它們只被發送到服務器。

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly

Scope of cookies(cookies 範圍)

Domain和Path指令定義cookie的範圍:cookie應發送到哪些URL。
Domain指定允許的主機接收cookie。如果未指定,則默認爲當前文檔位置的主機,不包括子域。如果指定了域,則始終包含子域。
例如,如果設置了Domain = mozilla.org,則cookie將包含在developer.mozilla.org等子域中。
Path表示在請求的URL中必須存在的URL路徑,以便發送Cookie標頭。 %x2F(“/”)字符被視爲目錄分隔符,子目錄也將匹配。
For example, if Path=/docs is set, these paths will match:

/docs
/docs/Web/
/docs/Web/HTTP     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章