A Web Design Blog


Sunday, April 20, 2014

Session hijacking would sound like something too big for newbies to php. Well here in this post I will be dealing with what is session hijacking and how to prevent it.


YOU MIGHT ALSO LIKE : What is and How To Prevent XSS Scripting in PHP - PHP Security

What is Session Hijacking ?

Session hijacking is a kind of a hacking method that an hacker can use to get access to other accounts provided that you are having a login system and you use sessions for that. Consider an example where you are using a session variable to store the username and password to check if the user is logged in. When a session gets started a cookie will be created with the name PHPSESSID and it will have a value that when the hacker acquires can add it to his browser and get access to the account of that person. Consider the following line of code :
session_start();

$_SESSION['username'] = "sri";

$_SESSION['password'] = "123";

Save it and open the page in your browser and open the cookies manager. You will observe that the following cookie would be created.



And when the hacker gets access to the content of the cookie he can write a piece of code to create a similar cookie on his browser with the same content and he would get access to the account of the user. And this is called session hijacking.

How To Prevent Session Hijacking :


Session hijacking is the most common method for hacking PHP sessions and in order to prevent that you can use the following two methods.

1. Hiding The Cookie :


Well note exactly hiding the cookie. The cookie would be visible by using this method but one cannot access it via browser script languages such as JavaScript. And so the user would be safe. To do so add the following piece of code right after you start the session.
ini_set('session.cookie_httponly', true);

2. Restricting with IP address :


And in this method we would be storing the IP from where the user logged in, in our session. And anyone else with IP other than the one in our session would be prevented from accessing the session variables. To do so add the following piece of code.
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR']; //add this before logging in the user

if($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']){   //add this check on top of every page shown after user logs in

session_unset();

session_destroy();

}

else{

//rest of your code

}

Working :



These two are the most effective ways for preventing session hijacking. Follow these and the hackers would be having a hard time. Happy Coding :D


A High School graduate. Addicted to Music, Web Design, Blogging, Web Development and Photoshop. Loves CSS a lot. Has 3 years of experience with blogging and 2 years with Web Design and Development.

2 comments:

  1. Really a good article on PHP hope ill implement this in my projects :)

    ReplyDelete