How To Set Cookies In Codeigniter

How To Set Cookies In Codeigniter


Cookies are small data files that store specific information about the sessions. This could login status and cart contents. These files are stored in a “Cookies” folder (the name could differ).
Creating and setting cookies in Codeigniter is easy because of a native helper class called (very appropriately) Cookie helper class. This class has all the necessary methods for creating, setting and managing cookies in your Codeigniter projects.

Creating the Cookies

To highlight how the Cookies helper class works, I will create a controller cw_cookies.php. This controller will have the following code:

The above code sets the cookies through
The helper is loaded using:

Pass information in Cookies

CodeIgniter offers two ways of passing information in the cookies.
The method is the Array Method that involves passing an associative array as a parameter in the set(). A typical example is:
This structure is set using the following:
In this method, only the first two parameters (name and value) are required. The expiration of the cookie is set through the expire parameter. This is the number of seconds the developer wishes to retain the cookie. If this duration is set to zero, the cookie will be removed once the browser is closed. The cookie can be made site-wide by adding a period before the domain name (.your-domain.com).
The second method involves passing individual parameters rather than the entire array. This method allows more control over the process of setting cookies because the developer could decide the parameters for the individual cookies. The prefered syntax is:

Fetch a Cookie

Once a cookie has been created, the next step is the process of fetching the cookie. The standard syntax is:
If the function cannot find the requested (first) parameter, it will return boolean FALSE.  (boolean)  if the item you are attempting to retrieve does not exist. The second optional parameter (when set to TRUE) will run the data through the XSS filter.

Conclusion

In this article I have discussed how to set cookie in CodeIgniter projects. The process is really easy and the developers have the option to set the cookies in two ways. Once the cookies have been set, fetching them is a breeze.

Comments