Monday, May 6, 2013

Codeignitor Session Example

Hi folks!, This simple post will explain Codeignitor session management in a vary simple coding example. In the first controller (s1.php) the sessions will be created. The send controller (s2.php) will print the session data and destroy previously added data. The third controller will again try to print the same data.

S1.php

load->library('session');
  $this->load->helper('url');
 }
 
 /*the first loading function*/
 function index(){
  echo "S1";
  $session_id = $this->session->userdata('session_id');
  echo "Session Id: ".$session_id;
  /*create session variable*/
  $this->session->set_userdata('uname','Anne');
  $data = $this->session->userdata('uname');
  echo "Newly Created Session var: ".$data;
  /*go to anotherpage link*/
  echo "<br>< a href=\"".base_url()."index.php/s2"."\">s2<a>";
 }
}

S2.php

load->library('session');
  $this->load->helper('url');
 }
 
 /*the first loading function*/
 function index(){
  echo "S2";
  $session_id = $this->session->userdata('session_id');
  /*get data from session and print*/
  $data = $this->session->userdata('uname');
  echo $data;
  /*destroy session*/
  $this->session->unset_userdata('uname');
  /*goto another page link*/
  echo "<br>< a href=\"".base_url()."index.php/s3"."\">s2<a>";
 }
}

S3.php

load->library('session');
  $this->load->helper('url');
 }
 
 /*the first loading function*/
 function index(){
  echo "S3";
  $session_id = $this->session->userdata('session_id');
  /*get data from session and print*/
  $data = $this->session->userdata('uname');
  if( isset($data) && !empty($data)){
   echo "Session Data: ".$data;
  }else{
   echo "Sesson data not found!";
  }
 }
}

No comments:

Post a Comment