我正在使用以下瘦身会话管理器(https://github.com/bryanjhv/slim-session)。我为login
,logout
和user_data
提供了单独的功能。
$app->post("/login", function() use ($app)
{
$input = $app->request()->getBody();
$input = json_decode($input);
try
{
if ($input->username && $input->password)
{
$user = Model::factory('Users')->where("username",$input->username)->where("password",md5($input->password))->find_one();
$session = new \SlimSession\Helper;
//set session
$session->set('userid', $user->id);
$status = 'success';
$message = 'Logged in successfully.';
}
else
{
$status = 'danger';
$message = 'Could not log you in. Please try again.';
}
}
catch (Exception $e)
{
$status = 'danger';
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message,
);
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
$app->post("/logout",function() use ($app)
{
try {
$session = new \SlimSession\Helper;
$session::destroy();
$status = 'success';
$message = 'You have been logged out successfully';
}
catch (Exception $e)
{
$status = 'danger';
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message
);
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
$app->get("/user_data", function() use ($app)
{
try
{
$session = new \SlimSession\Helper;
//get session
$userid = $session->get('userid');
$_SESSION['userid'] = $userid;
if ($_SESSION['userid'])
{
$users = Model::factory('Users')->where('id',$_SESSION['userid'])->find_one();
$response = array(
'id'=>$users->id,
'username'=>$users->username,
'email'=>$users->email,
'phone_number'=>$users->phone_number,
'password'=>$users->password,
'type'=>$users->type,
'credits'=>$users->credits,
'profile_picture'=>$users->profile_picture,
);
}
else
{
$status = "danger";
$message = 'You need to be logged in to do that.';
$response = array(
'status' => $status,
'message' => $message
);
}
}
catch (Exception $e)
{
$status = "danger";
$message = $e->getMessage();
$response = array(
'status' => $status,
'message' => $message
);
}
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
我遇到的问题是,当用户登录时,我在 / login 函数中设置了session
变量。但是,当我在 / user_data 函数中检索session
函数中设置的login
变量时,
任何人都知道发生了什么事?
答案 0 :(得分:0)
您是否已开始使用session_start()进行会话?
检查会话的正确逻辑如下:
if (isset($_SESSION['userid']))
{
// session exists
// do further work
}