Getting Facebooks' Cover Photo via PHP SDK & Graph API
Asked Answered
J

12

12

I'd like to know if there is a simple way of retrieving the Cover photo from a user in my application, via the Facebook php sdk.

I managed to retrieve the cover photo id of the album of the cover photo album, but my solution only works partially. (As you can see, it's not efficient, and If more albums will be added, and moved to other pages, thus this will not work).

    $albums = $facebook->api('/me/albums','GET');
    for($i = 0;$i<count($albums['data']);$i++){
        for($j = 0;$j<count($albums['data'][$i]);$j++){
            if($albums['data'][$i]['name'] == "Cover Photos"){
                echo $facebook->api('/me/albums/'.$albums['data'][$i]['cover_photo'],'GET');
            }
        }
    }
Jameyjami answered 14/11, 2011 at 17:54 Comment(1)
Do not vandalize your posts. By posting on this site, you've irrevocably granted the Stack Exchange network the right to distribute that content under the CC BY-SA 4.0 license for as long as it sees fit to do so. For alternatives to deletion, see: I've thought better of my question; can I delete it?Salena
B
36

Facebook seems to have added the Cover field to User Object recently

https://graph.facebook.com/facebookuserid?fields=cover will give you the user cover pic Details

Facebook Doc Link : http://developers.facebook.com/docs/reference/api/user/

Bobseine answered 25/5, 2012 at 6:26 Comment(6)
Not working again. There is no "cover" option in the api. developers.facebook.com/docs/graph-api/reference/v2.0/user/…Competency
This is still working Reference : developers.facebook.com/docs/graph-api/reference/v2.0/user . I checked /me?fields=id,name,cover with Graph Explorer Tool (developers.facebook.com/tools/explorer) and it gives the expected result.Bobseine
I can't seem to get it to work... Passing in the users ID into the username field returns { "error": { "message": "Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api", "type": "GraphMethodException", "code": 100 } }Biggers
I am trying to get this working with iOS and using the Facebook Graph API. Maybe this is not supported anymore? I seem to be able to access the cover photo in the Facebook debugger but only with an access tokenBiggers
Doesn't seem to work when getting an event with the JS SDK and by the responses here it sounds like it's not worth relying on it...Forwardness
how to get cover source of fb group in ios sdk or in Graph API ? Source 1 : developers.facebook.com/docs/graph-api/reference/v2.6/group Source 2: developers.facebook.com/docs/graph-api/reference/cover-photoWrong
B
25

I think the easiest is to use the graph api:

http://graph.facebook.com/{user_id or page_id}?fields=cover

and parse the returned JSON.

{
  "cover": {
    "id": "XXX", 
    "source": "https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash4/311205_989690200741_1231438675_n.jpg", 
    "offset_y": 66
  }, 
  "id": "XXXXXX"
}
Ballottement answered 22/3, 2012 at 19:10 Comment(3)
@Ballottement Your answer is quite helpful but can we get cover photo url directly ? As here we need to make dual call to get the final cover photo url?Cover
What permission do I need to request ? I did that. I keep getting.Merits
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500,"fbtrace_id":"CILN\/fxVBjn"}}Merits
F
9

Facebook has a really poor and outdated documentation... At the moment there isn't a proper way to do this via Graph API, but with FQL it is possible.

SELECT pic_cover FROM user WHERE uid='yourUserId'

The field pic_cover isn't documented but available. The response should look like this:

[
 {
  "pic_cover": {
   "cover_id": someId,
   "source": "someUrl",
   "offset_y": someOffset
  }
 }
]
Forum answered 23/2, 2012 at 15:44 Comment(2)
I think this is quite new. I din't see when I worked on my project.Jameyjami
Interesting. I used this method #5285121Pithy
A
4

The latest versions of Graph API (2.4 is current at the time of writing) support 'picture' field that returns user's profile picture. It's worth checking.

/<user-id>?fields=id,name,picture
Allotrope answered 17/8, 2015 at 23:58 Comment(0)
K
2

I think it is better to ask type of album then name.

$albums = $facebook->api("/me/albums");
$album_id = ""; 
foreach($albums["data"] as $item){
//echo $item["id"]." - ".$item["name"]." - ".$item["type"]." - ".$item["cover_photo"]."<br/>";
    if($item["type"] == "profile"){
        $album_id = $item["id"];
    $profile_picture_id = $item["cover_photo"];
    break;
    }
}
Kingdom answered 11/3, 2012 at 13:39 Comment(0)
P
1

Looks like at this stage, pending updated documentation from facebook, that your method is the only "sure fire" way to retrieve the cover of a users timeline.
If you find this method to be slow or inefficient - maybe you could try running it as a cron job and having a minimal update delay.. eg. run the cron twice a day (maybe even more), maybe handle two or three users at a time and have the cron running every 2 minutes... Not a solution per-say; more of a suggestion.

Payoff answered 14/11, 2011 at 18:41 Comment(4)
How can I retrieve a photo information vai it's id? or could I do something with FQL? I can possibly do anything with the id I got there.Jameyjami
sure - if you have a photo_id, all you have to do is query the graph api like this https://graph.facebook.com/{photo_id}. Or use fql like this :SELECT {any_fields_you_need} FROM photo WHERE pid={photo_id}Payoff
Thanks, it worked. But now I'd like to know how I can improve my code, by that I mean, how can I always find the cover photos album?Jameyjami
as far as I know, there is some sort of legal issue preventing facebook from pushing the new timeline feature to all the users, and with the timeline - cover photos. Perhaps once this is made public facebook will update their docs and we'll see an endpoint in the graph api for the cover photo...Payoff
H
1

I use: http://graph.facebook.com/{user_id or page_id}?fields=cover

Return on browser:

{
  "cover": {
    "id": "XXX", 
    "source": "https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash4/311205_989690200741_1231438675_n.jpg", 
    "offset_y": 66
  }, 
  "id": "XXXXXX"
}

How can I get field 'source' to a php varible?

Sr, I can't reply so i post here. :(

Headrick answered 19/6, 2013 at 4:37 Comment(0)
D
1

it tries to automatically recover from the image through php

$json = file_get_contents("https://graph.facebook.com/PROFILE_ID?fields=cover");
$obj = json_decode($json);
echo $obj->cover ->source;
Dismiss answered 5/12, 2013 at 19:46 Comment(0)
P
1

I use username instead of id and it works:

http://graph.facebook.com/{username}?fields=cover

Parse the JSON accordingly.

Pentose answered 2/8, 2014 at 8:34 Comment(0)
P
1

I have used https://graph.facebook.com/facebookuserid?fields=cover link but it did not work. When I search Facebook SDK documentation, I see the answer that works. I hope this will be helpful for you.

[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@?fields=cover", [user objectForKey:@"id"]]
                      completionHandler:^(
                                          FBRequestConnection *connection,
                                          id result,
                                          NSError *error
                                          ) {
                          NSLog(@"%@",[[result objectForKey:@"cover"]objectForKey:@"source"]);
                          /* handle the result */
                      }];

Result is a type of a Dictionary. You can see the link of user's cover photo under "cover" tag and its "source" tag also.

Pleistocene answered 15/4, 2015 at 6:53 Comment(0)
P
0

This is how I extracted my cover pic using Jackson and the Graph API.

        GraphRequest request = GraphRequest.newMeRequest(
                AccessToken.getCurrentAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        ObjectMapper mapper = new ObjectMapper();
                        try {
                            JsonNode actualObj = mapper.readTree(String.valueOf(object));
                            JsonNode cover = actualObj.get("cover");
                            Map<String,String> myMap = mapper.readValue(cover.toString(), HashMap.class);
                            Log.e("Cover link", myMap.get("source"));
                            coverpic = myMap.get("source");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "cover");
        request.setParameters(parameters);
        request.executeAsync();
Pagination answered 2/5, 2015 at 19:4 Comment(0)
G
0
function getCover() {
    FB.api('/me?fields=cover', function(response) {
       document.getElementById('cover').innerHTML =
          "<img src='" + response.cover['source'] + "' alt='' />"

    });
}
Goldi answered 9/10, 2015 at 10:42 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Basinet

© 2022 - 2024 — McMap. All rights reserved.