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

Sending and Receiving Cookies

This section describes how PHP supports cookies. setcookie() is the function to set a cookie to the HTTP response. $_COOKIE is the array containing cookies received in the next HTTP request.

PHP supports cookies with following elements:

1. setcookie() - A built-in function that defines a cookie to be sent in the HTTP response as a header line. Like other header lines, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. If output exists prior to calling this function, setcookie() will fail and return FALSE.

The syntax of calling setcookie() is:

bool setcookie(string name, string value, int expire)
  • "name" is the name of this cookie.
  • "value" is the value of this cookie. "value" is optional. If "value" is not provided, this cookie will be set in the HTTP response without any value.
  • "expire" is the time when this cookie should be expired. "expire" is optional. If "expire" is not provided, this cookie will saved in browser memory only. If "expire" is provided, it represents a time in number of seconds since the epoch. If the provided time is a future time, this cookie will be saved on the hard disk of the browser system.

For example, setcookie("user", "Herong") will set a cookie named as "user" in the HTTP response.

2. $_COOKIE - A built-in array that stores cookies returned back from the browser in the next HTTP request. Cookie names will be used as array keys. For example, $_COOKIE["user"] returns the cookie value, "Herong", included in the HTTP request.

Last update: 2005.

Sections in This Chapter

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

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