8.1. Setting Cookies

Problem

You want to set a cookie.

Solution

Use setcookie( ) :

setcookie('flavor','chocolate chip');

Discussion

Cookies are sent with the HTTP headers, so setcookie( ) must be called before any output is generated.

You can pass additional arguments to setcookie( ) to control cookie behavior. The third argument to setcookie( ) is an expiration time, expressed as an epoch timestamp. For example, this cookie expires at noon GMT on December 3, 2004:

setcookie('flavor','chocolate chip',1102075200);

If the third argument to setcookie( ) is missing (or empty), the cookie expires when the browser is closed. Also, many systems can’t handle a cookie expiration time greater than 2147483647, because that’s the largest epoch timestamp that fits in a 32-bit integer, as discussed in the introduction to Chapter 3.

The fourth argument to setcookie( ) is a path. The cookie is sent back to the server only when pages whose path begin with the specified string are requested. For example, the following cookie is sent back only to pages whose path begins with /products/:

setcookie('flavor','chocolate chip','','/products/');

The page that’s setting this cookie doesn’t have to have a URL that begins with /products/, but the following cookie is sent back only to pages that do.

The fifth argument to setcookie( ) is a domain. The cookie is sent back to the server only when pages whose hostname ends with the specified domain are requested. For example, the first cookie in the following ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.