PHP 5.4.x makes a few changes to the php.ini file which causes the Facebook PHP SDK to break, and after a few hours of searching, I’ve come across a solution that worked for me. The problem was that after authenticating an user using $facebook->getLoginUrl(), the subsequent $facebook->getUser() call would fail, retuning 0.

The issue is with the PHP SDK, which relies on $_REQUEST from the server, which has changed in PHP 5.4.0 because of default php.ini settings having been changed.

The solution is to change the SDK’s getCode() method (found in base_facebook.php file to work around the issue:

Replacing:

<?php
protected function getCode() {
if (isset($_REQUEST['code'])) {
if ($this->state !== null &&
isset($_REQUEST['state']) &&
$this->state === $_REQUEST['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $_REQUEST['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
?>

With:

<?php
protected function getCode() {
$server_info = array_merge($_GET, $_POST, $_COOKIE);
if (isset($server_info['code'])) {
if ($this->state !== null &&
isset($server_info['state']) &&
$this->state === $server_info['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $server_info['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
?>

The code simply combines the $_GET, $_POST and $_COOKIE arrays as with how $_REQUEST used to work prior to PHP 5.4.0. Hope this solution works for you as it did for me.

The change should then correctly return a valid User ID when calling $facebook->getUser(), instead of 0. This code also works in CodeIgniter, which is where I first tested the solution.