PHP - Upload a web hosted photo to facebook album via Graph API

安稳与你 提交于 2019-11-28 11:44:20

i think the problem is here:

$args[basename($file)] = '@' . realpath(file_get_contents($file));

since you want to post a picture from another source (right?), you should save it temporarily on your own host.

i also needed to do something like this, and since i had to process the image, i used the following way:

$im = @imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);

$args['image'] = '@' . realpath('imgs/temp/temp.jpg');

the rest looks fine though

I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:


Using the Graph API php sdk:

$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);

//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);

//To add to an album:
$fbk->api("/$albumId/photos", "POST", 
          array('source' => '@'. realpath($myPhoto), 'message'  => "Nice photo"));

//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST", 
          array('source' => '@'. realpath($myPhoto), 'message'  => "Nice photo"));

Using cURL directly:

If your really want to use cURL, your code is almost correct, but the error is in the $args array:

$args = array(
   'message' => 'Photo from application',
   'source' => file_get_contents($file)
  );

Since the key for the photo data is source, see the Facebook Doc


Note on the @ in cURL:

Also notice that the @ in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the @, so it isn't required if you already put in the source parameter the actual bytes.

I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.

No, that’s not the case.

But you need to give the full, publicly reachable HTTP URL to the image, without an @ in front – and you have to use the parameter name url for this value.

https://developers.facebook.com/docs/reference/api/photo/:

You can also publish a photo by providing a url param with the photo's URL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!