创建和管理对不同设备的远程服务

Create and manage remote services to different devices

我正在使用跨域并在登录时使用 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 app时,如何实现一个session?我的 运行 网站的运作方式是否相同?我只需要在 ajax 请求上添加会话代码吗?有什么想法吗?

为此,您需要一个主机服务器来对您的设备进行身份验证和对话。常见的协议是使用 cURLJSON 响应:

远程设备

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() 函数将执行正常的登录功能,只是它会在 timestamptokenapikeyusername数据库和 return 通过 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 值更新为当前时间。