Take the 2-minute tour ×

I made a few Facebook apps with the SDK a while ago, but now I want to try making one without using the SDK. I'm confused as to how access tokens work.

I think Facebook's PHP SDK stores the access token in a cookie, but most people on SO seem to store it in a database. Where should I store the access token?

If I store it in a database, do I store the user's ID in a cookie then?

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

This is verging on a discussion question, as the answer depends on what you want to do with it.

Just a quick reminder of the process:

  1. Get a token (from somewhere)
  2. Talk to Facebook and get the UserID associated with that token
  3. Update token (if looking for long access tokens)
  4. Store token (if you want to remember it for later)
  5. Do something with the UserID, validating the calls with the token.

The token is facebooks "SessionID". So long as you have a hold of the token, you can find the user that owned the token (if the token is still valid). You can keep hold of that token in the same way as you would a regular SessionID if you wrote your own session handler:

  • in a session variable ($_SESSION) which will persist while the PHP sessions is active
  • in a cookie ($_COOKIE) which will persist while the cookie is valid
  • by passing between webpages as a $_GET or $_POST variable
  • in a database - BUT you must have another SessionID under our own control (passed in $_SESSION, $_COOKIE, $_GET or $_POST) or another way of getting hold of the right token.

So, for run of the mill stuff, store in either session or cookie, depending on which suits your site better. It's simplest.

You'd only go to the complexity of storing in a DB for two purposes:

  1. You have another session system that is controlling your application (especially third party apps where you don't want to mess with their interal session system, so add your own wrapper on top)
  2. You want to do something when the user is no present (e.g. post to wall after a comment is approved in your own moderator system). In this case, you need the token to approve the post, but as the user is not there, you don't have access to $_COOKIE or $_SESSION etc.

Hope that helps.

share|improve this answer
add comment

Your Answer


