How to prevent session hijacking with php when all pages are loaded in index.php

Viewed 235

I am trying to build a login system in which I am using index.php?page=login as my login page and after logging in the page will be redirected to index.php?page=dashboard. The problem is my system is easily getting session hijacked so I need help to build it secure.

My index.php page

<?php

include 'config.php';

$session = new session();
$session -> start_session($conn, '_h', false);

$page = $_GET['page'];

if($page != 'login' && $page != 'register'){
  if (admin_logged_in() == false) {
  header("Location:index.php?page=login");
  exit();
  }

}


if($page != 'dashboard' && $page != 'password' && $page != 'login') {

}else {

    include $include.'/header.php'; 


    if(in_array("$page", $hidedesign))
    {

    }else{
      include $include.'/breadcrumb.php';
    }


} 

?>

<?php include $view; ?>


<!-- footer -->
<?php 

if($page != 'dashboard' && $page != 'password' && $page != 'login') {

}else {

    include $include.'/footer.php';

} 


?>

Config file

$conn = mysqli_connect("localhost","root","","db_name");

// $fg = 'hello';

// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


class session {
    public $db, $db_ref, $db_ads, $new_con;
    function __construct() {
    }

    function start_session($connection, $session_name, $secure) {
        if($secure==TRUE)
        {
            $httponly = FALSE;
        }
        else {
            $httponly = true;
        }

        $session_hash = 'sha512';

        ini_set('session.use_trans_sid', FALSE);
        ini_set('session.entropy_file', '/dev/urandom');
        ini_set('session.hash_function', 'whirlpool');
        ini_set('session.use_only_cookies', TRUE);
        ini_set('session.cookie_httponly', TRUE);
        ini_set('session.cookie_lifetime', 1200);
        ini_set('session.cookie_secure', TRUE);
        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
        session_name($session_name);
        $this -> db = $connection;
        //session_set_save_handler(array($this, 'open'), array($this, 'close'), array($this, 'read'), array($this, 'write'), array($this, 'destroy'), array($this, 'gc'));
        //register_shutdown_function('session_write_close');
        session_start();
        session_regenerate_id(true);

    }

}


function admin_logged_in() {

    if($_SESSION['ip'] != $_SERVER["REMOTE_ADDR"]){
        return false;
    }

    if($_SESSION['user_agent'] != $_SERVER["HTTP_USER_AGENT"]){
        return false;
    }

    if(!isset($_SESSION['admin_logged_in'])) {
        return false;
    }

    return true;
}

Login page code in views


$msg = '';

if(isset($_POST['submit'])){

  // $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
  $myusername = post_value_check($conn,$_POST['email']);
  $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  $mypassword = post_value_check($conn,$_POST['password']);

  $error_msg = array();
  $error = false;

  if($myusername  == ''){
    $error = true;
    $error_msg['myusername_error'] = 'Email is missing.';
  }else if(!preg_match($email_exp, $myusername)){
    $error = true;
    $error_msg['myusername_error'] = 'Enter a valid Email.';
  }

  if($mypassword  == ''){
    $error = true;
    $error_msg['mypassword_error'] = 'Password is missing.';
  }


  if($error == true ){

  }else{
    $q="select * from $tb_admin where email='$myusername'";
    $r=mysqli_query($conn,$q);
    if($r){
      $count = mysqli_num_rows($r);
      if($count > 0)
      {
        $ro = mysqli_fetch_array($r);
        $passm = $ro['password'];
        // $hashmpassword = 
        // if($passm==$mypassword){
        if(password_verify($mypassword, $passm)){

          // $session = new session();
          // $session -> start_session($conn, '_h', false);
          // session_regenerate_id(true);
          $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
          $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
          $_SESSION['admin_logged_in'] = 0;
          $_SESSION['id']=$ro['id'];
          $_SESSION['name']=$ro['name'];
          $_SESSION['email']=$ro['email'];

          echo"<script>location.replace('index.php?page=dashboard')</script>";
          exit();

          

        }else{

          $msg.='Password didnot match.';
        }
      }else{

        $msg.= 'No Email exist.';
      }
    }

  }

  extract($error_msg);
}

Logout

require 'config.php';
$session = new session();
$session -> start_session($conn, '_h', false);

session_destroy();

header('location:index.php?page=login');
exit();

So only a session file is generated in temp folder and everytime the page is reloading that file is changed but when I am trying to access the URL with incognito mode a different file is generated, so how can I prevent that to be happened also the session hijacking too.

1 Answers

I think you cannot prevent the other browser to stop generating the session file with the codes that you have written so far as because with every time you will reload the page a session file will be created on the existing session file like previously your session file was sess_98765eryu again when you will reload it will generate sess_324yiuyiui by replacing the first one. So now when you will open your link in different browser a new session file be generated but it will be blank if you will login with your credentials then the data will be filled into that new session file but again your session filename will be changed although the data in it will not change. I think this is a genuine process.

And to your session hijacking what codes you have implemented i think its true and also quite normal rather you can also study more about using Securing Session INI Settings along this you can also follow some good examples here how to prevent session hijacking with php. I hope this may help you. :)

Related