Welcome Guest, Not a member yet? Register   Sign In
Where is the best place to start my session? session_start()
#1

[eluser]Swammy[/eluser]
Basically every page on my site can be accessed by a logged in user. So how do I globally make sure the session is starting on every page refresh?

Code:
session_start()
#2

[eluser]anis2505[/eluser]
Just auto-load the session library( for CI 2.X ) or the session driver( for CI 3.X )

or if you wish load the session library/driver on your controller constructor
#3

[eluser]rose_anne[/eluser]
You can auto load the session. The location of the file is can be found in "application/config/autoload.php"
#4

[eluser]swgj19[/eluser]
I would create a MY_Controller,php located in the core that extends the CI_Controller. Then I would create an Admin_Controller.php located in libraries that extends MY_Controller. For example, see this below:

Code:
<?php
class Admin_Controller extends MY_Controller
{

function __construct ()
{
  parent::__construct();

  $this->load->library('api');
  $this->load->model('your_model');

  if ( ! $this->uri->segment(3, 0))
  {
   $this->is_logged_in();
  }
  
  $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");

}
  
  function is_logged_in()
{
  $is_logged_in = $this->session->userdata('is_logged_in');

  if(!isset($is_logged_in) || $is_logged_in != true)
  {
   echo 'You don\'t have permission to access this page.';
   echo anchor('login/index', 'Login');
   exit();  
   //$this->load->view('login_form');
  }  
}
}

Then just extend whatever class to the Admin_Controller

And to use the is_logged_in() function example:
Code:
function login_user()
{  
  $this->load->model('Membership_model');          
  $query = $this->Membership_model->validate();        
  //pass user's id(id created in model) in the login
  $id = $query['id'];
  // if the user's credentials validated...
  if($query)      
  {

   $data = array(
    'user_id' => $id,          
    'username' => $this->input->post('username'),
    //add value to session      
    'is_logged_in' => true            
   );
   //set session equal to $data array
   $this->session->set_userdata($data);
   //redirect to members area if session is true        
   redirect('site/members_area', 'refresh');          
  }
#5

[eluser]Swammy[/eluser]
Okay thanks guys. So if I am autoloading sessions I should be fine on a global level? Great.
#6

[eluser]Pert[/eluser]
If you are using custom sessions, you should start it in index.php file.

But yes, CodeIgniter sessions work very well, and allow you to do some cool stuff (automated flashdata!)




Theme © iAndrew 2016 - Forum software by © MyBB