Friday, July 1, 2011

Facebook And Caching

I've been doing a lot of Facebook/Flash game integration as of late and I recently ran into an incredibly annoying caching bug. Basically the integration works like this:

1) a "share" button in the game makes a call to Facebook's sharer.php script with a parameter pointing to a PHP file
2) this PHP file reads an XML file (specified via URL parameters) that contains the information that should appear in the Facebook post (link, title, picture URL, etc)
3) the PHP file uses this XML info to generate an HTML page with the appropriate metadata
4) Facebook's sharer.php script reads this HTML page to generate the Facebook post

Now, here's the problem. Facebook was caching an old version of the PHP file. As a result, I would try editing the XML to change, say, the title of the Facebook post, and my changes would fail to appear. Very troublesome.

The fix is quite simple. Facebook's sharer.php script works by passing in a 'u' parameter that holds the URI-encoded URL from which to generate the post. Here's an example pointing to Google:

http://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fgoogle.com

Facebook appears to cache the page that is specified in the 'u' parameter, so in order to force it to read a fresh version of the page, you can append a dummy parameter to the end of the URL. So instead of pointing it to http://www.google.com, I would instead point it to:

http://www.google.com?v=1

which would appear in the sharer script with URI-encoding as:

http://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fgoogle.com%3Fv%3D2

So in the Flash game, I generate a random number every time the share button is clicked and make a request to the sharer.php script with that random number tacked onto the end of the URL in the 'u' parameter. Take THAT Facebook.