Facebook SDK returned an error: Cross-site request forgery validation failed. The “state” param from the URL and session do not match

后端 未结 25 1021
南方客
南方客 2020-12-01 01:37

i\'m trying to get Facebook user id using the php sdk like this

$fb = new Facebook\\Facebook([
    \'app_id\' => \'11111111111\',
    \'app_secret\' =>         


        
25条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 02:38

    Finally, looking into FB code, I discovered that the problem

    Cross-site request forgery validation failed. Required param “state” missing

    and similars are caused by PHP variable $_SESSION['FBRLH_state'] that for some "strange" reason when FB call the login-callback file.

    To solve it I store this variable "FBRLH_state" AFTER the call of function $helper->getLoginUrl(...). Is very important to do only after the call of this function due to is inside this function when the variable $_SESSION['FBRLH_state'] is populated.

    Below an example of my code in the login.php:

    $uri=$helper->getLoginUrl($uri, $permissions);
    foreach ($_SESSION as $k=>$v) {                    
        if(strpos($k, "FBRLH_")!==FALSE) {
            if(!setcookie($k, $v)) {
                //what??
            } else {
                $_COOKIE[$k]=$v;
            }
        }
    }
    var_dump($_COOKIE);
    

    And in the login-callback.php before calling all FB code:

    foreach ($_COOKIE as $k=>$v) {
        if(strpos($k, "FBRLH_")!==FALSE) {
            $_SESSION[$k]=$v;
        }
    }
    

    Last, but not least, remember also to include code for PHP session so..

    if(!session_id()) {
        session_start();
    }
    ...
    ...
    ...
    ...
    
    

    I hope this response can help you to save 8-10 hours of work :) Bye, Alex.

提交回复
热议问题