How to manage session for a user logged in from mobile app in PHP?

PHPLover picture PHPLover · Feb 21, 2015 · Viewed 50.8k times · Source

I'm a PHP programmer by profession. So, I don't have any idea about iOS and Android coding.

The scenario is there is one website developed using a Social Networking PHP software titled "PHPFox".

Now there are two similar mobile apps which exactly replicates the functionality of this website. One mobile app is in iOS and another is in Android.

So, I've written a set of RESTful APIs where I'm accepting the request from mobile app, parse the request, pass the request parameters to the function which does the same job for website, get the response from this function, convert it into JSON format and sent it back to mobile app. For iOS and Android app I'm using the same set of REST API files.

When user logs in, the REST API for login gets called. Eventually the PHPFox function for authentication gets called, a security token is generated along with some other user data. With every login the different security token is generated by PHPFox. This data is set into the session. Now every time I call any of the functions through any REST API file the security token generated at the time of login is verified and only upon successful verification of token the PHPFox function gets called. This verification process is done internally by PHPFox. So no need to pass the security token explicitly or implicitly to any REST API call.

Till now everything works absolutely fine.

My doubt starts from here. I don't know whether the session is maintained in iOS/Android app. So, if session on server i.e. PHPFox gets timed out then what will happen to the app? Will it crash? Will the user have to login again? If user kills the app on the device and again comes to the app, does he/she have to do the login process again?

There are too many doubts in my mind. I get totally confused with these things.

Can someone please put more focus on the issue I'm facing? It would be really great if you could explain in detail.

Thanks.

Answer

valeriocomo picture valeriocomo · Feb 26, 2015

REST is sessionless for its nature. You need to generate a token when user logged in. You must save this token on your mobile client. For every request, you need to attach a valid token in request header and check it at server side. If token expires, the token stored on a client is not valid. So, you need to login again because of 401 response. If token it's not correct you need to responde 400. I hope that I'm helpful for you.