When we are doing web development, we usually use cookies or session to save the user's login status, verify whether the user has access to some pages that need to log in by checking the cookie or session data, this is done through the browser, this is the B/s architecture, But what if the client is a mobile app? Because this is the C/s architecture, it is not possible to use a cookie or session to verify the user's status, as if the browser has disabled cookies.
Fortunately, this is a workaround, in the case of disabling cookies, you can pass the session_id through Query_string, that is, after the app sends a login request, the server can pass session_id to the app, then the app saves the session _ID on mobile devices, in those functions that require login access, each interaction request is accompanied by a parameter session_id, routed to the server side, and the server-side checks the legitimacy of the session_id to determine if the user is logged in.
Here's a simple mobile development example that doesn't use native, but uses Appcan to build the app:
1. App Login Request:
- var url = ' http://127.0.0.1:8080/index.php?act=login&[email protected]&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, ' login failed! ', 4000);
- return;
- }
- }, ' json ',null, ' POST ', ', ' );
2. App Request user information:
- 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, ' username: '+uname, 4000);
- return;
- }Else{
- Uexwindow. Toast(0, 5, ' please login first! ', 4000);
- return;
- }
- }, ' json ',null, ' POST ', ', ' );
3. Server-side PHP response request [index.php]:
- <? PHP
- /**
- * User:wudiweb.com
- * App and server-side Simple example
- */
- 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 = = ' [email protected] ' && $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;
Note that this is only a simple usage, and if you think it is not perfect, you can extend it on this basis, such as encryption session_id.
Develop mobile app and server-side session state management and interaction