Gaurav
Gaurav

Reputation: 35

disable the back button in codeigniter?

I have developed a simple user management system. On user login I set database session. I also destroy them on logout. My Caching is also turned off. Even though when I click on back button on browser I can see my dashboard and when I click on any link, it should redirect me to login, but it shows me the dashboard at first, which is a bug.

controller in logins.php:

<?php
  class Logins extends CI_controller{

    public function index(){
        $this->load->view('login');

    }

    public function getdata(){
        
     $name = $this->input->post('name');
     $pass =$this->input->post('pass');
     $this->db->where('name =', $name);
     $this->db->where('pass =',$pass);
    // $this->db->where('status =', 'registered');
     $query=$this->db->get('form');

     if($query->num_rows()== 1)
     {
        $newdata = array(
                   'name'  => $name
               );

$this->session->set_userdata($newdata);
        //echo $name;
        $this->load->view('match',$name);
     }else 
     {
    redirect('logins');
    // $this->load->view('login');
     }
    }

    public function userlogout(){
        $this->session->unset_userdata('name'); 
         redirect('logins'); 

     }
  } 
?>
    

view page in match.php :

    <!DOCTYPE html>
    <html>
    <head>
    
        <title></title>
    </head>
    <body>
    
    <div>
    <?php
    
    $session_id = $this->session->userdata('name');
    
    echo "Hi  $session_id U Logged In";
    ?>
    </div>
    <div style="text-align:right;">
        <a href="<?php echo base_url()?>logins/userlogout">Logout</a>
    </div>
    
    </body>
    </html>

When I click on the back button, it show me the logged in page again.

Upvotes: 0

Views: 4332

Answers (3)

jackychua
jackychua

Reputation: 1

Try this.

public function getdata()
{
    ini_set('session.cache_limiter','public');
    session_cache_limiter(false);
}

Upvotes: 0

Nono
Nono

Reputation: 7302

"disable the back button in codeigniter?" - Not Possible by CodeIgniter

Why it's not possible?

CodeIgniter is a Server Side Scripting Web Framework, Its only responsible for it's own Environment not to Client Side e.g. like JavaScript. Hence, CI (CodeIgniter) does not affect Browser's Activity.

Now, I am assuming you want to Prevent Views/Content being display for Un-Authorized User, when User Log Out and try to see Dashboard or any other Content (which is made only for Login User) by hitting Browser Back Button.

Basically it's very straight foreword that Browser maintained Self Session (Active) to works faster like, we can see old Entered Data in Form after submitting the form and going back, by back button. So, once user fill the login form and submit the form they will be redirect on Login/Dashboard page, once they Click on Log Out Button CI destroy the User's Session Data. But in side this story Browser Cache the Content and Form Data & hence when user clicks on History Back Button they would be still able to see the from data or Cache Content.

So, what we can do ?

Well, we can use Cache Headers in our Application Response to tell Browser, 'Hey! Mozilla/Chrome/Browser Do Not Cache/Store this Page, It's not Cacheable & Always Knock The Door. But.. in this scenario a little problem still exist..

Oh No!! Now what :( ?

Well, Cache Header will Prevent to being content display by removing the content from Browser History. But if a page amused by any type of Form Submission then it's very likely user might be ask for 'Confirm Form Submission'. If they just Submit The Form Again or Press 'F5' button Form will be submit again by same Previous Data or Form Input.

Okay, So how we can deal this Confirm Form Submission in CodeIgniter..?

We can use OTT (One Time Token), CSRF (Cross-Site Request Forgery) Protection or Any Other Method which is Intend to Made only for One Time. Like CI has CSRF Regenerate option to Create a New CSRF Toke every time. You can find the option in application/config.php in CSRF Section $config['csrf_regenerate'], just make this $config['csrf_regenerate'] = TRUE.

Still able to submit form..?

Oh Yes! Why.. because you set the $config['csrf_regenerate'] = TRUE; But $config['csrf_expire'] still has long time period to Expire Old CSRF Token. So if you set the $config['csrf_expire'] = 60; then you won't be able to re Submit The Cache Form By Browser Back Button. Because old CSRF token expired & CI don't recognized same old form after 2 minutes, we sat the Expire CSRF token by 2 minutes here...Yuhooo!!

He Hey!! seems it's solved :) Yes!

Here is completely new Controller Logins.php Code:


<?php
// security first always....
(defined('BASEPATH') or exit('No direct script access allowed'));
/**
 * Class Controller
 *
 * Class Logins Controller to handle login & logout
 */
class Logins extends CI_controller
{
    /**
     * Class Constructor
     */
    public function __construct()
    {
        // execute parent class constructor
        parent::__construct();
        // load helpers
        $this->load->helper(array('form', 'url', 'security'));
        // load lib
        $this->load->library('form_validation');
        // prevent from Browser Cache
        $this->output->set_header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
        $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
        $this->output->set_header('Pragma: no-cache');
        $this->output->set_header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    }
    /**
     * Default method to execute if method name missing
     * @return [type] [description]
     */
    public function index()
    {
        // check if user login or not
        if (!$this->session->userdata('name')) {
            // show login view
            $this->load->view('match');
        }
        // if already logged in, show other view
        else {
            // get name from session login flag
            $name = $this->session->userdata('name');
            // load view
            $this->load->view('match', $name);
        }
    }
    /**
     * login Form POST Method to verify Users identity
     * @return [type] [description]
     */
    public function getdata()
    {
        // if POST made then only
        if ($this->input->post()) {
            $rules = array(
                array(
                    'field' => 'name',
                    'label' => 'Name',
                    'rules' => 'trim|required|xss_cleaned|min_length[3]|max_length[25]',
                ),
                array(
                    'field' => 'pass',
                    'label' => 'Secret Password',
                    'rules' => 'required',
                ),
            );
            // form validation
            $this->form_validation->set_rules($rules);
            // check validation
            if ($this->form_validation->run() === false) {
                $this->load->view('match');
            } else {
                // safe from CSRF, use 2nd param as TRUE in POST
                $name = $this->input->post('name', true);
                $pass = $this->input->post('pass', true);
                // Query Where Conditioning
                $array = array('name' => $name, 'pass' => $pass, 'status' => 'registered');
                // produces: WHERE name = 'user-name' AND pass = '***' AND status = 'registered'
                $this->db->where($array);
                // get from MySQL Table
                $query = $this->db->get('form');
                // if result
                if ($query->num_rows() > 0) {
                    $sess_login = array(
                        'name' => $name,
                    );
                    // set session login flag
                    $this->session->set_userdata($sess_login);
                    // load view
                    $this->load->view('match', $name);
                } else {
                    redirect('logins');
                }
            }
        } else {
            redirect('logins');
        }
    }
    /**
     * Log Out Method
     * @return [type] [description]
     */
    public function userlogout()
    {
        $this->session->unset_userdata('name');
        redirect('logins');
    }
}

Here is completely new Views match.php Code:

<?php
$name = $this->session->userdata('name');
?>
<!DOCTYPE html>
<html>
<head>
    <title>CodeIgniter First Login</title>
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="jumbotron vertical-center">
        <?php if ($name !== false): ?>
            <div class="container">
                <div class="alert alert-success">Wohoo!! You made it.. <?php echo $name ?> <a href="<?php echo base_url()?>logins/userlogout" class="btn btn-danger">Log Out</a></div>
            </div>
        <?php else: ?>
            <div class="container">
                <?php echo (validation_errors()) ? '<div class="alert alert-danger">'.validation_errors().'</div>' : ''; ?>
                <?=form_open('logins/getdata', 'class="form-controller"'); ?>
                <fieldset>
                    <legend>Login Information</legend>
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" name="name" id="name" placeholder="Please enter your user name here" value="<?php echo set_value('name'); ?>">
                    </div>
                    <div class="form-group">
                        <label for="password">Secret Password</label>
                        <input type="password" class="form-control" id="password" name="pass" placeholder="Please enter your password here" value="<?php echo set_value('pass'); ?>">
                    </div>
                </fieldset>
                <div class="form-group row">
                  <div class="offset-sm-2 col-sm-10">
                    <button type="submit" class="btn btn-primary">Sign in</button>
                </div>
            </div>
            <?=form_close();?>
        </form>
    </div>
<?php endif ?>
</div>
</body>
</html>

config.php


$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 120; // 2 minutes
$config['csrf_regenerate'] = TRUE;

Upvotes: 2

Sonali Hajarnis
Sonali Hajarnis

Reputation: 187

Controller :- Check session exist or not in constructor where dashboard view load

<?php


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


        if(!$this->session->userdata('name')) 
        {
            redirect('logins');
        }

    }




?>

Upvotes: 0

Related Questions