Wednesday, June 27, 2012

Cookie and Session in PHP

Cookie is similar to session to store temporary data. The difference is that cookie stores data in browser and user can block cookie setting in browser. For independent browser setting, session is better. Below are some tips:
1.  How long will my session  last  in PHP?
 This is set in php.ini:
session.gc_maxlifetime = 1440
which is 1440 seconds, i.e 24 minutes

We can also set it in PHP scripts: for example set it as 30 minutes
ini_set(’session.gc_maxlifetime’, 30*60);
In my LMS web design, I prefer to set session maximum time 10 hours so users have enough time to do exam on-line and browse content.
@ini_set('session.gc_maxlifetime', '36000'); /* 10 hours */
2, session example:
 To start a session:
<?php session_start(); // start up your PHP session! ?>
To store some data in session: for example test_session.php
<?php session_start(); $_SESSION['views'] = 1; // store session data ?>
To retrieve session data: retrieve_session.php, remember to add session_start(); at the beginning:  
echo "views = ". $_SESSION['views']; //retrieve data
To destroy a session

<?php session_start(); session_destroy(); ?>

3. Cookie example:
$value = 'Test';
setcookie("MyCookie", $value, time()+3600);  /* expire in 1 hour */
$MyCookie = $_COOKIE['MyCookie'];

No comments:

Post a Comment