PHP Sessions

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn’t maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

PHP sessions can use cookies depending on how you configure them. Have a look at these settings:

session.use_cookies (boolean): specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled).
session.use_only_cookies (boolean): specifies whether the module will only use cookies to store the session id on the client side. Enabling this setting prevents attacks involved passing session ids in URLs. This setting was added in PHP 4.3.0. Defaults to 1 (enabled) since PHP 5.3.0.

If you disable session cookies, a GET parameter is used instead.

Sessions can also be stored in the DB instead of the default storage.
Useful command : session_set_save_handler() to override.

http://culttt.com/2013/02/04/how-to-save-php-sessions-to-a-database/

session_start(); 

// store session data
$_SESSION['views']=1;

//retrieve session data
echo "Pageviews=". $_SESSION['views'];

// typical use 
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];

// unset data
if(isset($_SESSION['views']))
  unset($_SESSION['views']);

// destroy session 
session_destroy();

Leave a Reply