CodeIgniter User Guide Version 1.7.3


Cookie Helper

The Cookie Helper file contains functions that assist in working with cookies.

Loading this Helper

This helper is loaded using the following code:

$this->load->helper('cookie');

The following functions are available:

set_cookie()

Sets a cookie containing the values you specify. There are two ways to pass information to this function so that a cookie can be set: Array Method, and Discrete Parameters:

Array Method

Using this method, an associative array is passed to the first parameter:

$cookie = array(
                   'name'   => 'The Cookie Name',
                   'value'  => 'The Value',
                   'expire' => '86500',
                   'domain' => '.some-domain.com',
                   'path'   => '/',
                   'prefix' => 'myprefix_',
               );

set_cookie($cookie);

Notes:

Only the name and value are required. To delete a cookie set it with the expiration blank.

The expiration is set in seconds, which will be added to the current time. Do not include the time, but rather only the number of seconds from now that you wish the cookie to be valid. If the expiration is set to zero the cookie will only last as long as the browser is open.

For site-wide cookies regardless of how your site is requested, add your URL to the domain starting with a period, like this: .your-domain.com

The path is usually not needed since the function sets a root path.

The prefix is only needed if you need to avoid name collisions with other identically named cookies for your server.

Discrete Parameters

If you prefer, you can set the cookie by passing data using individual parameters:

set_cookie($name, $value, $expire, $domain, $path, $prefix);

get_cookie()

Lets you fetch a cookie. The first parameter will contain the name of the cookie you are looking for (including any prefixes):

get_cookie('some_cookie');

The function returns FALSE (boolean) if the item you are attempting to retrieve does not exist.

The second optional parameter lets you run the data through the XSS filter. It's enabled by setting the second parameter to boolean TRUE;

get_cookie('some_cookie', TRUE);

delete_cookie()

Lets you delete a cookie. Unless you've set a custom path or other values, only the name of the cookie is needed:

delete_cookie("name");

This function is otherwise identical to set_cookie(), except that it does not have the value and expiration parameters. You can submit an array of values in the first parameter or you can set discrete parameters.

delete_cookie($name, $domain, $path, $prefix)