[英]PHP - Upload a web hosted photo to facebook album via Graph API
我正在嘗試將托管的www(例如http://www.google.se/intl/zh_CN/images/srpr/logo1w.png )文件上傳到Facebook相冊。
創建相冊效果很好,但是我似乎沒有上傳任何照片。 我正在使用facebook php-sdk( http://github.com/facebook/php-sdk/ ),而我已經嘗試過的示例是:
如何使用Facebook Graph API將照片上傳到相冊
我猜測CURL上傳也許只能管理本地存儲的文件,而不能管理網絡托管的文件。
這是我的代碼:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '@' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_token'];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the photo id
print_r(json_decode($data,true));
...其中附件-> guid包含照片網址。
我現在幾乎陷入困境...
我認為問題出在這里:
$args[basename($file)] = '@' . realpath(file_get_contents($file));
由於您要發布其他來源的圖片(對嗎?),因此應將其暫時保存在自己的主機上。
我還需要執行類似的操作,並且由於必須處理圖像,因此我使用了以下方式:
$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');
其余的看起來不錯
我建議使用Facebook php SDK ,它會更容易使用,並且該代碼可與API的將來更新一起使用:
使用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"));
直接使用cURL:
如果您確實要使用cURL,則您的代碼幾乎是正確的,但是錯誤在$ args數組中:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
由於照片數據的密鑰是source
,請參閱Facebook文檔
注意cURL中的@:
還要注意,cUrl中的@
表示該參數將被@
之后的文件的實際字節替換,因此如果您已經在source
參數中輸入了實際字節,則不需要此參數。
我猜測CURL上傳也許只能管理本地存儲的文件,而不能管理網絡托管的文件。
不,不是這樣。
但是,您需要為圖像提供完整的,可公共訪問的HTTP URL,並且前面沒有@
–並且必須使用參數名稱url
作為該值。
https://developers.facebook.com/docs/reference/api/photo/ :
您還可以通過提供帶有照片URL的
url
參數來發布照片。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.