简体   繁体   中英

Prevent session hijacking in PHP

I wrote the log In/log Out scripts of my web page and when the user logs in I store in the $_SESSION variable the user agent. Now each time a page is loaded I check if the user is logged in or not and if it is logged in I check if the user agent has changed or is still the same to prevent hijacking. In case it has changed I call my logOut() function:

function logOut($conn) 
{
    $sql = "UPDATE Users SET logged='no' WHERE username='" . $_SESSION['username'] ."'";
    $conn->query($sql); 

    // Unset all session values 
    $_SESSION = array();

    // get session parameters 
    $params = session_get_cookie_params();

    // Delete the actual cookie. 
    setcookie(session_name(), '', time() - 42000, 
    $params["path"], 
    $params["domain"], 
    $params["secure"], 
    $params["httponly"]);

    // Destroy session 
  session_destroy();    
}

Now the problem is that the right user can still navigate my website as logged in while I would like to have it logged out. What could be the problem?

To test this code I logged in using Mozilla Firefox and I copied the value of the cookie in Chrome and reloaded the home page and as expected I am unable to log in with Chrome but if I reload the page in Mozilla it is still logged in.

It's better use unset() function ,for instead unset($_SESSION['username'])

Also I can say you ,your codes have sql injection vulnerability in here

' $sql = "UPDATE Users SET logged='no' WHERE username='" . $_SESSION['username'] ."'"; '

because everyone can with use curl , modify the variable username to ' or '1'='1 and inject this to

your webpage and get access ,so you can modify this line to

$sql = "UPDATE Users SET logged='no' WHERE username='" . stripslashes($_SESSION['username']) ."'"; '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM