Session hijacking

How can you prevent a session hijacking?

// Session hijacking: She gets the new genereated id // Defence: Store in session $_SERVER['HTTP_USER_AGENT'] (does not change between requests) Rather than providing one of his own, an attacker may gain a user's valid session identifier. For example, suppose that a user logs in. If the session identifier is regenerated, they have a new session ID. What if an attacker discovers this new ID and attempts to use it to gain access through that user's session? It is then necessary to use other means to identify the user. One way to identify the user in addition to the session identifier is to check various request headers sent by the client. One request header that is particularly helpful and does not change between requests is the User-Agent header. Since it is unlikely that a user will change from one browser to another while using the same session. <?php // Secure php.ini settings ini_set("session.use_trans_sid", 0); // default 0 ini_set("session.use_cookies", 1); // default 1 ini_set("session.use_only_cookies", 1); // default 1 session_start(); if (isset($_GET['btn_submit'])) { if ($_GET['username'] == 'john') { $_SESSION['username'] = 'john'; session_regenerate_id(true); // At every login PHPSESSID is changed $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT']; // --- Look Here --- // // Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 .... } } echo "Sessionid: " . session_id() . " / Logged user: " . @$_SESSION['username'] . "<br>"; echo "User_Agent: " . $_SERVER['HTTP_USER_AGENT']; // if (! @$_SESSION['username']) { if (@$_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']) { die("Hijack attempt"); } } // In another browser // // Output: Hijack attempt // --- Look Here --- // ?> <?php if (! @$_SESSION['username']): ?> <form method="GET"> Username: <input type="text" name="username" value="john"/><br /> Password: <input type="password" name="password" /><br /> <input type="submit" name="btn_submit" value="Log In"/> </form> <?php endif; ?>