Session with PHP

The premise of a session is that data is stored on the server, not in the Web browser and a Session identifier is used to locate a particular user's record (session data).

 

  ex.: 


  session_start();

  $_SESSION['first_name'] = $row[1];

  $_SESSION['name'] = 'Jessica';


  • 1st line, start's the session
  • 2nd and 3rd line, assign's a value to or for registration   Prior to version 4.1 PHP use the following steps or procedures:

  ex.: 


     session_start();

     $name = 'Jessica';

     session_register('name');

     $first_name = $row[1];

     session_register('first_name');



Session_Start()


  • every PHP script that either sets or access session, variables must use the session_start() function
  • this line must be included before any call to the "header.inc" or related include statements or any require statements


Accessing Session Variables


  syntax: 


   $_SESSION[' variable name ']

   $HTTP_SESSION_VARS


  ex.: 


  session_start();

  IF ( !isset($_SESSION['first_name'])) {


   Header("location: http://" .    $_SERVER['HTTP_SELF'] .    dirname($_SERVER['PHP_SELF']) .    "/index.php");

   exit();

  }


  $page_title = 'Logged In';

  include ('top/header.inc');


  . . . . . .

  . . .



Delete Session Variables


  The following are to be use for removing or deleting an existing Session variable(s) and as follows:


  syntax: 


  unset() 

      for single variable use only.

      ex.: 

         unset( $_SESSION[' var '] );

  array() 

      reset the whole Session array by assign'n an Empty array.

     ex.: 

           $_SESSION = array();

  session_destroy() 

        remove all task from the server side



Changing the Session Behavior


  syntax: 


      init_set( parameter, new_setting );


  ex.: 


      init_set( 'session.save_path', '/path/to/folder');



  • Changes where session data will be stored, the default is /tmp   syntax: 

      session_name ('var');


  ex.: 


      session_name ('YourVisitID');


  • is a user define session_name and is a lot friendier
  • for session_name() to work, it must be called before every use of session_start() in your Web Application

  ex.: 


   session_name ('myvisitID');

   session_start();

   . . . . .

   . . ...



Garbage Collection


  Note: 


   session_gc_maxlifetime = 1,440


   session_gc_probability = 30


   controls the frequency of how temporary data will be removed from the system when not in use any more or when not needed at all.




Accessing Arrayed Session Variables


  ex.: 


  session_start();


  if (!is_array($_SESSION['sesCart']))

  {

      $_SESSION['sesCart'] = array();

  }


   $intFlgUnique = 1;


   for ($intCtr=0; $intCtr < count($_SESSION['sesCart']); $intCtr++)

   {

        if ($_SESSION['sesCart'][$intCtr]["id_itm"] == $intItmID)

        {

              $intFlgUnique = 0;

         }

   }