Search code examples
phpfacebooklocationfacebook-php-sdkphoto

How to add location to a post or a photo with facebook php sdk


This is driving me nuts.

Can anyone post a practical example on this? My gratitude for life:

  1. Publish a post and add the related checkin/location info
  2. publish a photo and add the related checkin/location info.

In both cases the user delegates the action to the app. We have the access token by prior.

Please no theory, a working coding snipper ;-)

I am particularly messed up because facebook asks a nested structures of objects and arrays

Any help would be really appreciated


Solution

  • Grab the $user instance

    $user = $facebook->getUser();
    

    Check if the logged in user is authenticated.

    if ($user) {
      try {
        // Proceed 
        $user_profile = $facebook->api('/me');
      } catch (FacebookApiException $e) {
        error_log($e);
        $user = null;
      }
    }
    

    Present the login url with permissions needed for posting. Specifically the publish_streampermission as stated in the photo documentation http://developers.facebook.com/docs/reference/api/user/#photos

    if ($user) {
      $logoutUrl = $facebook->getLogoutUrl();
    } else {
      $loginUrl = $facebook->getLoginUrl(array(
                 'scope' => 'read_stream,publish_stream,user_photos'
                 ));
    }
    

    Place the me/photos call in a try/catch block to catch any exceptions that may occur.

        try {
            $facebook->setFileUploadSupport('http://yourapicallingwebsite.com/');
            $response = $facebook->api(
              '/me/photos/',
              'post',
              array(
                'message' => 'Testing the Photo Upload',
                'source' => '@/path/to/img',
                'place' => 'place_id' 
              )
            );
          }
       catch (FacebookApiException $e) {
           error_log('An error occurred posting the image');
       }
    

    Check the response from the me/photos call

    $photo_u = $facebook->api('/'.$response['id']);
    

    Display it if your like

    <img src=<?php echo $photo_u['picture'] ?>/>
    

    Check the place name if you like

    $photo_place = $photo_u['place'];
    <span><?php echo $photo_place['name'] ?></span>