PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

Sending and Receiving Cookies in PHP Scripts

This chapter provides tutorial examples and notes about cookie. Topics include understanding of the cookie concept; sending cookies with the setcookie() function; receiving cookies with the $_COOKIE array; enabling output buffering; creating persistent cookies; specifying cookie domain and path.

What Is a Cookie?

Sending and Receiving Cookies

Sending and Receiving Cookies - Example

ob_start() - Output Buffering Function

Persistent Cookies Saved on Hard Disk

Other Cookie Properties - Domain and Path

Conclusion:

  • setcookie() must be called before any output to the HTTP response. The main reason is that PHP is not buffering the HTTP response. But you can alter this behavior by using the ob_start() functions.
  • A persistent cookie is stored in a cookie file on the browser's local machine.
  • A persistent cookie can have an expiration time expressed in number of seconds since epoch.
  • Web browser will only send back a cookie when both domain and path match the requested domain and path.
  • To make a cookie available for all sub domains of a top level domain, set the domain property to the top level domain name.

Dr. Herong Yang, updated in 2009
Sending and Receiving Cookies in PHP Scripts