[Prestashop Developement] Use Cookie & Session in a PrestaShop Module
In a Prestashop modules or Prestashop System, the Prestashop does not allow use $_SESSION, $_COOKIE because security reasons
if you want to stored your temporarily variables in cookie or session. you can use global Cookie object from Prestashop System.
1.if you are in a controller or a class extends from Module class, you can use global Cookie object throught
$cookie = &$this->context->cookie;
or directly use
$this->context->cookie
if you are in another placements, you can use global Cookie object throught
$cookie = Context::getContext()->cookie;
Note: Context::getContext()->cookie like $this->context->cookie
2. add, update a key/value in global Cookie object
you can add/update a pair of key/value with 2 ways
1st solution:
$cookie->__set(‘key1’, ‘value 1’);
$cookie->__set(‘key2’, ‘value 2’);
…
// then write it to browser
$cookie->write();
2nd solution:
Directly assign value for property of Cookie object
$cookie->key1 = “value 1”;
$cookie->key2 = “value 2”;
..
// then write it
$cookie->write();
3. read, remove a key/value from Cookie
You can use key/value as a property of cookie object
example, print it:
echo $cookie->key1;
or you can use __get method
echo $cookie->__get(‘key1’);
if you want to remove a key/value from Cookie object, you can use 2 ways:
- set key to null
$cookie->key1 = null
- Or use __unset method
$cookie->__unset(‘key1’);
Some another methods from Cookie object, you can open file
PRESTASHOP_ROOT\classes\Cookie.php
4. Cookie of Backoffice is difference Cookie of Frontend
If you are in a Front controller or any PHP files, PHP classes which only use in Frontend. But you want use Cookie of Backoffice in some cases: check admin permission, check user is admin, check admin user logged in, get id_employee, get translation string of Backoffice from Frontend…
You can use global Cookie object of Backoffice through creating a Cookie Object from admin:
$cookie = new Cookie(‘psAdmin’);
Example, in a Front Controller we can print ID_ADMIN who logged in Prestashop Backoffice
$cookie = new Cookie(‘psAdmin’);
echo $cookie->id_employee;
Leave a reply
You must be logged in to post a comment.