ZCE 5.3


Cookies & Sessions

Cookies allow your application to store a small text file on client Web broweser.

<?php // Set a cookie on the client setcookie('hide_menu', '1'); if ($_COOKIE['hide_menu'] == 1) { echo 'Hide Menu'; } ?>
  You can provide an expiration time.
<?php setcookie('hide_menu', '1', 3600); // 1 hour ?>
  Cookies values must be scalar
<?php setcookie('hide_menu', array()); // Warning: setcookie() expects parameter 2 to be string
There are three more arguments:
<?php // path - where cookie will be accesible // domain - allowed domani // secure - the browser only send cookie in case of HTTPS setcookie('hide_menu', '1', 86400, '/path/', '', 1); // a day ?>
  You can create arrays using the same array.
<?php setcookie('test[0]', "foo"); setcookie('test[1]', "bar");
To delete a cookie, set time negative
<?php setcookie("hide_menu", false, -3600);
Keep in mind that the amount of storage available is severely limited therefore, use sessions instead. If you want to set cookie for another domain, it can not be done. Session can be started from your script.
<?php session_start(); ?>
  Also, you can start session automaticaly in php.ini
session.auto_start = 1 ; no need to include session_start() in every script ; session is started before loading classes and makes storing objects in the session impossible
For accesing date we use $_SESSION.
<?php // Set a session variable $_SESSION['hide_menu'] = true; // From here on, we can access hide_menu in $_SESSION if ($_SESSION['hide_menu']) {}
  Sessions are used to create persistent client state between request. Sessions are stored on servers, cookies on clients. In the interest of security, it is a good idea to follow your call to session_start() with a call to session_regenerate_id() whenever you change a user's privileges to prevent "session fixation" attacks.