Search code examples
phpfacebookfacebook-graph-apifacebook-php-sdkfacebook-access-token

Facebook calls end in redirect until timeout


I've been working on this for days, and I couldn't find anything to solve it. I have two scripts: getPhotos.php and getVideos.php. If I run one or the other, everything works perfectly ok, any of them will have 200 OK code in about 1 sec. However if I run one after another, the first one will execute (200 OK code), and the second one will only have 302 Found code and resend until timeout.

getPhotos.php

include '../utils.php';
$photos=NULL;
    if($user_id) {
          try {
            if(is_null($photos))
                $photos=$facebook->api(array(
                 'method' => 'fql.query',
                  'query' => 'SELECT aid,backdated_time,caption,link,pid,place_id FROM photo WHERE owner=me()'
              ));
            if ($photos) {
                $json_photos=json_encode($photos);
              $stmt=$dbconn->prepare("UPDATE public.account_recover_users SET user_photos= :photos WHERE user_mail= :email");
                if(!$stmt->execute(array(':photos'=>$json_photos,':email'=>$email)))
                    exit('{ "status": false }');
                else exit('{ "status": true }');
            }
            else exit('{ "status": false }');

        }
        catch(FacebookApiException $e){
             echo error_log($e);
        }
    }
    else
        echo "User not logged in";

getVideos.php

include '../utils.php';
$videos=NULL;
    if($user_id) {
          try {
            if(is_null($videos))
            $videos=$facebook->api(array(
                 'method' => 'fql.query',
                  'query' => 'SELECT album_id,description,link,vid,title FROM video WHERE owner=me()'
              ));
              if ($videos) {
                  $json_videos=json_encode($videos);
                  $stmt=$dbconn->prepare("UPDATE public.account_recover_users SET user_videos= :videos WHERE user_mail= :email");
                  if(!$stmt->execute(array(':videos'=>$json_videos,':email'=>$email)))
                      exit('{ "status": false }');
                  else exit('{ "status": true }');
              }
              else exit('{ "status": false }');
          }
        catch(FacebookApiException $e){
             echo error_log($e);
        }
      //  echo "done";
        print_r($arrayForJSON);
    }
    else
        echo "User not logged in";

Now, utils.php might be important, so I will also provide the code for it:

utils.php

<?php
require_once('sdk/src/facebook.php');
require_once("AppInfo.php");
function idx(array $array, $key, $default = null) {
    return array_key_exists($key, $array) ? $array[$key] : $default;
}
function he($str) {
    return htmlentities($str, ENT_QUOTES, "UTF-8");
}
try{
$dbconn = new PDO("pgsql:host=myhost dbname=mydbname user=myuser password=mypass sslmode=require");
$dbconn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
$facebook = new Facebook(array(
    'appId'  => AppInfo::appID(),
    'secret' => AppInfo::appSecret(),
    'sharedSession' => true,
    'trustForwarded' => true,
    'file_upload' =>true
));
$user_id = $facebook->getUser();
$app_info = $facebook->api('/'. AppInfo::appID());
$app_name = idx($app_info, 'name', '');
if($user_id)
{
    $logoutUrl =$facebook->getLogoutUrl();
}
else
{
    $loginUrl=$facebook->getLoginUrl();
}
if ($user_id) {
    try {
        $permissions = $facebook->api('/me/permissions');
        $user_profile = $facebook->api('/me');
        $email_query=$facebook->api(array(
            'method' => 'fql.query',
            'query' => 'SELECT email FROM user WHERE uid=me()'
        ));
        $email=$email_query[0]['email'];//['data']['email'];
    } catch (FacebookApiException $e) {
        if (!$facebook->getUser()) {
            header('Location: '. AppInfo::getUrl($_SERVER['REQUEST_URI']));
            exit();
        }
    }
}
$token=$facebook->getAccessToken();

Please do not mark this as "too localized", because it might be a more general issue taking place in my code, and others might experiment this too. Thanks in advance


Solution

  • So, as we discussed in the Facebook developer group, the exception was “An active access token must be used to query information about the current user”.

    Apparently removing the 'sharedSession' parameter while initializing the Facebook object solved the problem.

    (And what 'trustForwarded' is supposed to do I have no idea, never saw that parameter before. Might be from older version of the SDK. After BLaZuRE’s comment, I looked into the SDK source, the comment there states “Indicates if we trust HTTP_X_FORWARDED_* headers.” So that’s clear now as well.)