1/25/2012

[php で OAuth を使ってみる:第六回] Facebook に画像を post する

Facebook に OAuth を使って画像を post してみる。
※この情報は 2012 年 1 月現在のものです。仕様が変更される可能性は充分にあるので、ご了承ください。

OAuth を使った認証の流れは Facebook に文字を post する を参照。

post する
下記の php をアプリのディレクトリにアップする(予め tmp ディレクトリを 707 で作っておく)
<?php
// 一度自分のサーバにアップ
$uploaddir = './tmp/';
$photo = $uploaddir. basename($_FILES['img']['name']);
move_uploaded_file($_FILES['img']['tmp_name'], $photo);

require_once 'facebook/facebook.php';

$facebook = new Facebook(array(
  'appId' => 'xxxxxxxxxxxxxxxx', // 以前のエントリーで確認した「App ID/API Key」
  'secret' => 'xxxxxxxxxxxxxxxx' // 以前のエントリーで確認した「アプリの秘訣」
));

$attachment = array(
  'access_token' => $_COOKIE['facebookToken'], // 以前のエントリーで cookie に保存した access_token
  'message' => 'テスト', // post する本文
  'src' => '@'. $photo, // 必ず $photo の前に '@' を付ける
);

$facebook->setFileUploadSupport(true);
$post_result = $facebook->api('/me/photos', 'POST', $attachment);

// 自分のサーバにアップした画像を削除
unlink($photo);

echo "<script type='text/javascript'>alert('「". $status. "」をpostしました!');</script>\n";
?>

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.