Monday, April 20, 2009

PHP code for preventing session hijacking



The hacker may get session id of our browser in someway, and then using this session id they can continue our session in their browser.

So this session hijacking will allow the hacker to use our login restricted web pages without knowing our login credential.

Say for example, the hacker can read your emails from their browser itself if they just know session id of your browser.

Find below the sample code written in PHP for preventing session hijacking.



function prevent_session_hijacking()
{
//code for preventing session hijacking
session_start();

//Regenerate SessionID for avoiding Sesssion Fixation

if (!isset($_SESSION['initiated']))

{
session_regenerate_id();
$_SESSION['initiated'] = true;

}

//for preventing session hijacking.
if (isset($_SESSION['HTTP_USER_AGENT']))

{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))

{
exit;

}

}

else

{
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}

}



We have to do many other Security testing (e.g sql injection, Cross-site scripting) to make sure your website is safe for your users.
More Articles...

No comments:



Thanks for visiting our blog


twitterrss facebook linkedin YouTube subscribe


Subscribe via email

Enter your email address: