简体   繁体   中英

Check if session IP matches current IP - PHP

So I am checking an session IP against the current session. I have had a look at the the questions that may have my answer and none of them do.

What happens is that everytime I connect, I get 'Your IP doesn't match...'

<?php
if (isset($_SESSION['ip']) and (strcmp($_SESSION['ip'], md5($_SERVER['REMOTE_ADDR'])))){
    echo "Your IP doesn't match your session, your IP: ". $_SERVER['REMOTE_ADDR'] ." and your session IP: ". $_SESSION['ip']. ". <a href='/scripts/signout.php'>Click here to log out.</a>";
    die;
}
?>

I know to use HTTPX and will implement that after I fix this. Also $_SESSION['ip'] is the md5(Current IP)

you are comparing session ip and md5 of ip address, so probably you need:

<?php
if (isset($_SESSION['ip']) and ((strcmp($_SESSION['ip'], $_SERVER['REMOTE_ADDR']) !== false))){
    echo "Your IP doesn't match your session, your IP: ". $_SERVER['REMOTE_ADDR'] ." and your session IP: ". $_SESSION['ip']. ". <a href='/scripts/signout.php'>Click here to log out.</a>";
    die;
}
?>

strcmp returns 0 if the strings match, and in php that will equal false, also you don't need the md5 call really.

<?php
if (isset($_SESSION['ip']) && strcmp($_SESSION['ip'], $_SERVER['REMOTE_ADDR']) !== 0){
    echo "Your IP doesn't match your session, your IP: ". $_SERVER['REMOTE_ADDR'] ." and your session IP: ". $_SESSION['ip']. ". <a href='/scripts/signout.php'>Click here to log out.</a>";
    die;
}
//or you can just go 

if(isset($_SESSION['ip']) && $_SESSION['ip'] !== $_SERVER['REMOTE_ADDR']) {
/// stuff
}

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