Authentication and PHP API Sessions

I have a PHP application that is highly session dependent. Now we are considering creating an API for our users. Our initial thoughts are that users need to authenticate against api with their email address, password and API key (unique to each user).

However, since the current application (including models) makes extensive use of user sessions, I am not sure of the best approach.

Assuming the API request is authenticated correctly, it would be acceptable:

  • Starting a session to call the API after user authentication
  • Run models and return json / xml to user
  • Kill the session

This means that a session is created for each API call, and then immediately cleared. This is normal? Or should we consider other alternatives?

+7
source share
1 answer

In my experience creating APIs, I found that it is best for sessions to continue for just one request and recreate session information in each run loop.

This clearly leads to overhead if your session instance is significant, however, if you just check the credentials against the database, that should be fine. In addition, you should be able to cache any heavy lifting in something like APC or memcache based on the user ID, not the session, reducing the work required to recreate the session while providing authentication in every request.

+1
source

All Articles