Reputation: 3245
Today I learned the difference between COOKIES and SESSION.
Now I would like to create a login. The main idea is the following:
$ip = $_SERVER['REMOTE_ADDR'];
$session_ip = $_SESSION['PHPSESSID']['ip'];
if ( (session_id() === $_COOKIE['PHPSESSID']) && ($ip === $session_id) ){
return (true);
} else {
return (false);
}
I would like to check if the IP is the same like that one that an User had last time when he logged in.
So when the SESION starts it will create the $_COOKIE['PHPSESSID']
on client site. The server will store the SESSION some where on the server and can identify the SESSION with session_id()
Basically it should be the same like this part says:
session_id() === $_COOKIE['PHPSESSID']
Now, the probem is the part saving the IP to that SESSION.
How can I access this SESSION to handle it like an Array? Normally I would do it like this:
$ip = $_SERVER['REMOTE_ADDR'];
$_COOKIE['PHPSESSID']['ip'] = $ip;
So I just save the IP to the client site $_COOKIE['PHPSESSID']
but what about the SESSION from the server site? How can I store the IP there?
Thanks alot.
Upvotes: 0
Views: 2599
Reputation: 71414
Saving IP to session would be as easy as:
session_start(); //near beginning of script
$_SESSION['ip'] = $ip;
Than on any additional pages after ip value has been set:
session_start(); //near beginning of script
if(!empty($_SESSION['ip'])) {
// do something with it
}
I can't think of any reason you would work with the $_COOKIE['PHPSESSID']
value directly.
I would say though that I don't quite understand why you would need to store this value to session as it would always be available via $_SERVER['REMOTE_ADDR']
.
To answer the use case specified in your comment. Your code could be as simple as:
session_start(); //near beginning of script
if(!isset($_SESSION['ip'])) {
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
} else if ($_SERVER['REMOTE_ADDR'] !== $_SESSION['ip']) {
// invalid session
// exit program, redirect, or whatever you want to do here
// just make sure you exit script execution
}
// continue with rest of code
Upvotes: 6
Reputation: 528
If you want to check if the last-login IP equals to the current used IP, you have to store your data on your database instead of using sessions. One of the general behaviour of sessions is that any session-data is lost after the session reaches his end of life.
Upvotes: 0
Reputation: 770
Looks like you're trying to block connections MIM attack by requiring the IP address not to change? This might be problematic - because IP's don't always stay the same in the real world. However, you could do:
<?php
//start a session
session_start();
//check cookie and ip
if((session_id() === $_COOKIE['PHPSESSID']) && (!isset($_SESSION['ip']) || (isset($_SESSION['ip']) && $_REQUEST['REMOTE_ADDR'] === $_SESSION['ip']))){
echo 'attempt ok';
} else {
die('IP changed');
}
//set ip in session
if(!isset($_SESSION['ip'])){
$_SESSION['ip'] = $_REQUEST['REMOTE_ADDR'];
}
Upvotes: 1