phpimagefacebookfacebook-graph-apiupload

Error uploading picture to facebook using PHP: OAuthException: An active access token must be used to query information about the current user


I am simply trying to upload an image to the user's timeline using PHP. After my app is installed I am using the following code but getting the error: OAuthException: An active access token must be used to query information about the current user.

I am able to echo an access token via the $token variable so I know its there. I've looked everywhere and tried to fix it but no success. Heres the code...

<?php  

include_once "src/facebook.php";  
$app_id = 'xxxxxx';  
$application_secret = 'xxxxxx';  

$facebook = new Facebook(array(  
'appId'  => $app_id,  
'secret' => $application_secret,  
'cookie' => true, // enable optional cookie support  
));  
if ($facebook->getUser())
{
  $user = $facebook->getUser();
  //die($token);

        try
        {
            $token = $facebook->getAccessToken();
            $facebook->setFileUploadSupport(true);
            $file = "5star.png";
            $post_data = array(
            "message" => "My photo caption",
            "source" => '@' . realpath($file)
            );
            //die("/me/photos/?access_token=$token");
            $data['photo'] = $facebook->api("/me/photos?access_token=$token", 'post', $post_data);
        } catch (FacebookApiException $e)
        {
            die($e);
        }

header( 'Location: http://google.com' ) ;
}else
{
  $loginUrl = "https://graph.facebook.com/oauth/authorize?type=user_agent&display=page&client_id=$app_id&redirect_uri=http://apps.facebook.com/yourprofilerating/&scope=user_photos,email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown";  
  echo "<script> top.location.href='" . $loginUrl . "'</script>";
}

?>

Solution

  • You may have an invalid or expired access token, check out Handling Invalid and Expired Access Tokens. Insert the code provided in this article before the api call and after the declaration of $token.