PHP Cookie Components
In this chapter you will learn:
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
Cookie Component
As you can see, a cookie contains a number of pieces of information, summarized in the following table:
Cookie Field | Example | Description |
---|---|---|
name | fontSize | The name of the cookie. |
value | 3 | The value of the cookie. |
expires | Tuesday | The 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.com | By 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. |
Secure | Secure | This 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. |
HttpOnly | HttpOnly | This 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:
- What is PHP setcookie() function
- Syntax for PHP setcookie() function
- Parameters for PHP setcookie() function
- Note for PHP setcookie() function
- Example - Set each fields for a cookie
- Example - Leave field unset for a cookie
- Example - setcookie() send and receive
- Example - delete a cookie by set the expiration date to the past
- Example - setcookie() and arrays
Home » PHP Tutorial » PHP Cookie