PHP Cookie Components

In this chapter you will learn:

  1. HTTP Header
  2. Cookie Component
  3. Note for cookie domain

HTTP Header

A cookie is sent from the server to the browser as part of the HTTP headers. Here's an example of an HTTP header to create a cookie:

Set-Cookie: fontSize=3; expires=Tuesday, 26-Jan-2013 17:53:08 GMT; path=/;  
domain=.example.com; HttpOnly   

As you can see, a cookie contains a number of pieces of information, summarized in the following table:

Cookie FieldExampleDescription
namefontSizeThe name of the cookie.
value3The value of the cookie.
expiresTuesdayThe cookie expire time. When this point is reached, it is deleted. If this value is set to zero, or omitted, the cookie lasts as long as the browser is running, and is automatically deleted when the browser exits.
path/The path that the browser should send the cookie back to. For example, if you specify a path of /user/ , only scripts contained in the /user/ folder (and any subfolders) will receive the cookie. If you don't specify a value, the current directory of the script is assumed. A value of "/" means to send cookie to all URLs in your Web site.
domain.example.comBy default, a browser only sends a cookie back to the exact URL that sent it. Cookie from www.example.com will only be sent back to URLs that begin with http://www.example.com. URLs beginning with http://example.com or http://www2.example.com won't receive the cookie. However, if domain is set to .example.com the browser will send the cookie back to all URLs within this domain.
SecureSecureThis field, if present, indicates that the cookie should be sent only if the browser has made a secure (https) connection with the server. If it's not present, the browser will send the cookie to the server regardless of whether the connection is secure.
HttpOnlyHttpOnlyThis field, if present, tells the browser that it should make the cookie data accessible only to scripts that run on HTTP. Attempts to access the cookie via JavaScript within the Web page are rejected. This can help to reduce cross-site scripting (XSS) attacks.

Note

We can't access cookies from other domains. For example, if your Web site at www.example.com tries to set a cookie with a domain value of www.google.com, the cookie will be rejected by the browser.

Next chapter...

What you will learn in the next chapter:

  1. What is PHP setcookie() function
  2. Syntax for PHP setcookie() function
  3. Parameters for PHP setcookie() function
  4. Note for PHP setcookie() function
  5. Example - Set each fields for a cookie
  6. Example - Leave field unset for a cookie
  7. Example - setcookie() send and receive
  8. Example - delete a cookie by set the expiration date to the past
  9. Example - setcookie() and arrays
Home » PHP Tutorial » PHP Cookie
PHP Cookies
PHP Cookie Components
PHP setcookie() function
PHP Access Cookies
PHP Remove Cookies