Reputation: 291
im using xampp, my session is always lost when im using my IP instead of localhost/ how can i keep the session? it works ok if i use localhost/
<?php
require '/mysqli.php';
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json');
$myJson = json_decode(file_get_contents('php://input'));
$action = $myJson->action;
session_start();
if($action == 'login') {
$myJson->password ? $role='admin' : $role='encoder';
$_SESSION['username'] = $myJson->username;
$_SESSION['role'] = $role;
$_SESSION['id'] = session_id();
if($role =='admin'){
$sql = "SELECT * FROM `users` WHERE `username`='".$myJson->username."' AND `password`='".md5($myJson->password)."'";
// $_SESSION['status'] =
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) == 1){
$_SESSION['status'] = "Login success.";
} else {
session_unset();
session_destroy();
$_SESSION['status'] = "Login failed.";
}
} else {
$_SESSION['status'] = "Login success.";
}
} else if ($action == 'logout') {
session_unset();
session_destroy();
$_SESSION['status'] = "Logged out.";
} else if ($action == 'check' && session_id() == ''){
$_SESSION['username'] = $_SESSION[''];
$_SESSION['role'] = $_SESSION[''];
$_SESSION['id'] = $_SESSION[''];
var_dump($_SESSION);
}
echo json_encode($_SESSION);
?>
Upvotes: 0
Views: 506
Reputation: 1771
well the problem here is that a session has a unique session ID which is generated with your connection to the server.
therefore if you connect with localhost your IP is 127.0.0.1
and if you start the session with your actual ip you have something like: 192.168.0.10
and a new session ID is generated and hence started.
a possible way to workaround this is to enter a host entry into your host file.
the question is: what do you want to achieve? Do you switch the URLs while testing? if yes, why?
Upvotes: 1