Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match
Solution 1:
I found that as long as I enabled PHP sessions before generating the login url, and at the top of the script Facebook eventually redirects to, it works just fine on its own without setting a cookie (as per ale500's answer). This is using the 5.1 version of the sdk.
At the top of both scripts, I added...
if(!session_id()) {
session_start();
}
...and it "just worked".
Here's a barebones complete example that worked for me:
auth.php
if (!session_id()) {
session_start();
}
$oFB = new Facebook\Facebook([
'app_id' => FACEBOOK_APP_ID,
'app_secret' => FACEBOOK_APP_SECRET
]);
$oHelper = self::$oFB->getRedirectLoginHelper();
$sURL = $oHelper->getLoginUrl(FACEBOOK_AUTH_CALLBACK, FACEBOOK_PERMISSIONS);
// Redirect or show link to user.
auth_callback.php
if (!session_id()) {
session_start();
}
$oFB = new Facebook\Facebook([
'app_id' => FACEBOOK_APP_ID,
'app_secret' => FACEBOOK_APP_SECRET
]);
$oHelper = self::$oFB->getRedirectLoginHelper();
$oAccessToken = $oHelper->getAccessToken();
if ($oAccessToken !== null) {
$oResponse = self::$oFB->get('/me?fields=id,name,email', $oAccessToken);
print_r($oResponse->getGraphUser());
}
Why?
As an additional note, this is explained in the Docs on the repo. Look at the warning on this page.
Warning: The FacebookRedirectLoginHelper makes use of sessions to store a CSRF value. You need to make sure you have sessions enabled before invoking the getLoginUrl() method. This is usually done automatically in most web frameworks, but if you're not using a web framework you can add session_start(); to the top of your login.php & login-callback.php scripts. You can overwrite the default session handling - see extensibility points below.
I'm adding this note because it's important to keep in mind should you happen to be running your own session management or if you're running multiple web servers in parallel. In those cases, relying upon php's default session methods won't always work.
Solution 2:
insert this code after $helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];
Solution 3:
Lots of great answers already mentioned, here is the one which helped for me,
I found that the problem is Cross-site request forgery validation failed. Required param “state” missing in FB code and here is the solution
After this line
$helper = $fb->getRedirectLoginHelper();
Add the below code,
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}