咱们进行web开发的时候,通常使用cookie或session来保存用户的登陆状态,经过检查cookie或session的数据来验证用户是否具备对某些须要登陆的页面的访问权限,这一切都是经过浏览器来完成,这是b/s架构,可是,假如客户端是移动应用端,那该怎么办?由于这是c/s架构,没法使用使用cookie或session来检验用户的状态,此时的状况就好像浏览器禁用了cookie。php
庆幸的是,这是有解决方法的,在禁用cookie的状况下,能够经过query_string来传递session_id,即在app发送登陆请求后,服务器端能够经过传递session_id到app,而后app保存session_id在移动设备上,在那些须要登陆访问权限的功能,每一次交互请求附带参数session_id,传送到服务器端,再由服务器端检查session_id的合法性来肯定该用户是否已登陆。html
如下是一个简单的移动开发示例,并无使用原生的,而是使用appcan来构建app:web
1. app登陆请求:json
- var url = 'http://127.0.0.1:8080/index.php?act=login&email=aa@qq.com&pwd=123456';
- $.getJSON(url,function(res){
- if(res.ok == 'yes'){
- var storage = window.localStorage;
- if(storage) storage.setItem('sid',res.session_id);
- }else{
- uexWindow.toast(0, 5, '登陆失败!', 4000);
- return;
- }
- }, 'json',null, 'POST', '', '');
2. app请求用户信息:浏览器
- var sid = '';
- var storage = window.localStorage;
- if(storage) sid = storage.getItem('sid');
- var url = 'http://127.0.0.1:8080/index.php?act=uinfo&session_id='+sid;
- $.getJSON(url,function(res){
- if(res.ok == 'yes'){
- var uname = res.username;
- uexWindow.toast(0, 5, '用户名:'+uname, 4000);
- return;
- }else{
- uexWindow.toast(0, 5, '请先登陆!', 4000);
- return;
- }
- }, 'json',null, 'POST', '', '');
3. 服务器端php响应请求[index.php]:服务器
- <?php
- /**
- * User: wudiweb.com
- * app与服务器端简单示例
- */
- header("Content-Type: text/html; charset='utf-8'");
- session_start();
-
- $act = $_REQUEST['act'];
- $result = array('ok' => 'yes');
-
- if($act == 'login'){
- $email = $_REQUEST['email'];
- $pwd = $_REQUEST['pwd'];
-
- if($email == 'aa@qq.com' && $pwd == '123456'){
- $result['session_id'] = session_id();
- }else{
- $result['ok'] = 'no';
- }
- }elseif($act == 'uinfo'){
- $session_id = $_REQUEST['session_id'];
- if($session_id == session_id()){
- $result['username'] = 'Wudiweb';
- }else{
- $result['ok'] = 'no';
- }
- }
-
- echo json_encode($result);
- exit;
注意,这只是一个简单的用法,若是你认为不够完善,能够在此基础上进行扩展,例如加密session_id等。cookie