简体   繁体   中英

Graph API Get all photos

i have a website where people can upload pictures to be rated/liked etc. I am developing a function where if they don't want to upload pictures they can import them from there Facebook account.

I can login/logout the user from Facebook using the PHP Graph API but i am not sure on the request i need to get the logged in persons photos. I have setup the login url to the user_photos permissions.

I had a feature like this a few years ago where i would use the FQL to query the images but now i am using the new Facebook v4 Graph API.

Any help will be appreciated.

FacebookSession::setDefaultApplication( 'ID', 'SECRET' );
$helper = new     FacebookRedirectLoginHelper('URL');
$permissions = array(
'user_photos'
);
try {
if ( isset( $_SESSION['access_token'] ) ) {
    // Check if an access token has already been set.
    $session = new FacebookSession( $_SESSION['access_token'] );
} else {
    // Get access token from the code parameter in the URL.
    $session = $helper->getSessionFromRedirect();
}
} catch( FacebookRequestException $ex ) {

// When Facebook returns an error.
print_r( $ex );
} catch( \Exception $ex ) {

// When validation fails or other local issues.
print_r( $ex );
}
if ( isset( $session ) ) {

// Retrieve & store the access token in a session.
$_SESSION['access_token'] = $session->getToken();
// Logged in
echo 'Successfully logged in!';
} else {

// Generate the login URL for Facebook authentication.
$loginUrl = $helper->getLoginUrl($permissions);
echo '<a href="' . $loginUrl . '">Login</a>';
}

After user has made the login you can get photos like so:

FacebookSession::setDefaultApplication($APP_ID, $APP_SECRET);  

$session = new FacebookSession($access_token);

$response = (new FacebookRequest($session, 'GET', '/me/photos?fields=source&limit=100'))->execute();
$object = $response->getGraphObject();
$arr = self::convertToAssoc($object);

put in the limit param your value.

here is how you convert the facebook-object:

public static function convertToAssoc($graphObject){
        $arr = $graphObject->asArray();
        if ( !array_key_exists('data', $arr) ){
            $arr['data'] = '';
        }
        $arr_data = $arr['data'];

        $data = [];
        foreach($arr_data as $item){
            $data[] = get_object_vars($item);   
        }

        return $data;    
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM