Developer Blog

  • Blog
  • /
  • Cookie handling in PHPixie
By Dracony on 27 August 2013

PHPixie has just been updated with a new feature: managing cookies. Cookies are much less secure than session variables, since they can be modified by the user and therefore cannot be trusted to hold sensitive information, they are still a very handy tool to have. One reason for using cookies is that you don’t need to waste disk space storing this kind of user data, especially if you want to set long-living variables that shouldn’t expire soon.

Using cookies in PHPixie is very similar to using session. Here is a quick example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$pixie->cookie->set('fairy', 'Tinkerbell');

//Upon the next browser request
//get the cookie
$pixie->cookie->get('fairy'); 

//remove cookie
$pixie->cookie->remove('fairy');

//You can also pass additional parameters similar to the setcookie() function
$lifetime = 60*60; // 1 hour lifetime
$path = '/'; //URL path where the cookie will be available
$domain = 'phpixie.com' //Domain of the cookie
$secure = true; //If true the cookie will only be available over HTTPS
$http_only = true; //If true the cookie will not be availble in Javascript

$pixie->cookie->set('fairy', 'Tinkerbell', $lifetime, $path, $domain, $secure, $http_only);

To avoid redundancy in setting same cookie parameters you can add default parameters to cookie.php config file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// /assets/config/cookie.php
<?php
return array(
    'lifetime' => 60*60,
    'path' => '/',
    'domain' => 'phpixie.com',
    'secure' => true,
        'http_only' => true
);

```> Note that the cookies are not being sent immediately like when using setcookie(), instead they are sent together with the Response. Meaning that if you stop script execution using _die()_, _exit()_ or an exception occurs the cookies will not be sent.

I hope youll like this new addition to the PHPixie =]

comments powered by Disqus