Facebook PHP SDK infinite redirect
Ever run into an infinite loop of redirections when trying to authenticate with Facebook ? There are multiple reasons for this, but the most common one is that your redirect uri does not match what Facebook expects. If by any chance you left the value empty expecting the SDK to figure it out and redirect your request back, there are a few things you need to consider:
you are behind a decent load balancer and SSL accelerator, in which case you need to initialise the Facebook class with 'trustForwarded' => true. This will trust the headers coming from the load balancer and set https properly for your uri.
you also need to make sure that your server supports $_SERVER['HTTPS']. Apache does that by default, but other servers, like nginx need additional configuration changes for this.
That's all. Here is the bit of code that ruined my night last night:
protected function getHttpHost() {
if ($this->trustForwarded && isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
return $_SERVER['HTTP_X_FORWARDED_HOST'];
}
return $_SERVER['HTTP_HOST'];
}
protected function getHttpProtocol() {
if ($this->trustForwarded && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
return 'https';
}
return 'http';
}
if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] == 1)) {
return 'https';
}
return 'http';
}
Other than that seems that the new version of PHP-SDK 3.2.1 does not allow to get the token multiple times. At some point the sdk runs getAccessTokenFromCode() which is supposed to use the current code to get a token. Make sure you cache this token, as you cannot get another one with the same code. If you are using the Facebook JS SDK, the code is taken from the fbsr cookie and it changes with each page load, but if you are planning to use this multiple times on the same page, just cache the token. It's the most sane thing to do considering the unnecessary extra requests.
Let me know if my rambling helped in any way.








