我正在使用跨域并使用php服务器在登录时获取用户信息。在我运行的网站中我使用php代码,当用户登录时我添加了此代码
session_start();
然后在成功登录时声明用户信息,如:
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_email'] = $user['user_email'];
$_SESSION['user_name'] = $user['user_name'];
然后我在每个用户请求中使用该会话$user['user_id'];
。
如何在用户登录Hybrid应用程序时实施会话?我的网站运作方式是否相同?我只需要在ajax请求中添加会话代码吗?有什么想法吗?
答案 0 :(得分:1)
要执行此操作,您需要一台主机服务器,该服务器将对您的设备进行身份验证和通信。常见的协议是使用cURL
和JSON
响应:
远程设备
1)您的设备,我将使用另一台服务器,因为它很容易,将使用cURL启动连接:
function cURL($variables = false)
{
$url = "http://www.example.com/";
$query = (!empty($variables))? '?'.http_build_query($variables) : '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url.$query);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if(!empty($response))
$data = json_decode($response,true);
curl_close($ch);
return $data;
}
$login = cURL(array(
'service'=>'login',
'apikey'=>123123,
'username'=>'whatever',
'password'=>'whatever')
);
print_r($login);
API主机服务器
2)然后您的服务器将监听服务。我使用$_GET
,但$_POST
更好:
if(!empty($_GET['service'])) {
switch($_GET['service']) {
case('login'):
logInUser($_GET);
}
}
logInUser()
函数只会执行正常的登录功能,只是它会在数据库中设置timestamp
,token
,apikey
和username
。通过json成功回归:
//...authentication code here...//
if($valid) {
// However you want to make a token
$token = md5($usename.mt_rand(1000000,9999999).time());
// Do code here to save the username, token, apikey, timestamp into database
// This will then echo back the token on success to the device
die(json_encode(array('token'=>$token,'success'=>true)));
}
else {
die(json_encode(array('token'=>'','success'=>'bad username/password')));
}
在此之后,设备使用查询字符串中的令牌以及apikey回调主机。它还包括服务以及服务将数据发送回设备所需的任何变量。每次命中服务器都会触发服务器查找apikey,然后服务,然后如果服务不是login
,则需要令牌。它将查询数据库并检查数据库中的所有内容是否有效。如果令牌存在且时间戳足够快(您可以设置到期时间),则服务运行。服务运行后(或完成之前),令牌的timestamp
值将更新为当前时间。