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

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


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.


Unlike web browsers, iOS and android apps cannot maintain sessions. Usually, once a user has logged in (login credentials verified from server), its login credentials are saved on client side. Then the app gets data from server using session less REST api calls. This is how mostly it is done in mobile applications.

However, if you want the server session and mobile app go hand in hand (which i don't think is a good idea), the way is

1) When the user logs in, a security token is generated on the server side and saved on both server and client side.

2) The mobile app will be able to communicate with the server as long as the security token is valid.

3) When the session expires, the security token becomes invalid. Now there must be an understanding between server and client about the response when the session is expired. Now the mobile app must redirect the user to login page again. The user will login again and then communicate with the server. This should happen every time the session is expired.


If your are using Oauth 2 for athentication, here is the common setup:

  • User logs in on mobile app
  • If the credentials are ok, the server returns the access token, a refresh token and the token's lifetime
  • The mobile app stores those values + current timestamp
  • On the server's side, a garbage collector is configured to clear expired tokens
  • Before making any api call, the mobile app checks if the token is about to expire (with the help of the stored values). If the token is about to expire, the app sends the refresh token which instructs the server to generate a new access token
  • If you want users to stay connected, the app can be configured to check the access token periodically and request a new one if it's stale

Hope this helps.

Cheers