Skip to content

Instantly share code, notes, and snippets.

@upsilon
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save upsilon/b36992d52044fa56800b to your computer and use it in GitHub Desktop.
Save upsilon/b36992d52044fa56800b to your computer and use it in GitHub Desktop.
opOpenSocialPluginでアルバム画像をアップロードする
<?php
// http://oauth.googlecode.com/svn/code/php/OAuth.php を使用
require_once 'OAuth.php';
// api.php の URL
$baseUri = 'http://sns.example.com/api.php';
// http://sns.example.com/pc_backend.php/connection/new で発行
// 使用するAPIに「OpenSocial API: メンバー/フレンド情報の取得」を選択
$consumerKey = 'xxxxxxxxxxxxxxxx';
$consumerSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$consumer = new OAuthConsumer($consumerKey, $consumerSecret);
// アルバムを所有しているメンバーID
$ownerId = '1';
// 画像を追加する先のアルバムID (前もって作成する必要がある)
$albumId = '1';
// アップロードする画像のパス
$imagePath = './image.png';
// ここから上は環境に応じて適宜変更する
$uri = $baseUri.'/social/rest/mediaitems/@me/@self/'.$albumId;
$request = OAuthRequest::from_consumer_and_token($consumer, null, 'POST', $uri);
$request->set_parameter('token_type', 'admin');
$request->set_parameter('xoauth_requestor_id', $ownerId);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, null);
$boundary = '----------'.md5(microtime());
define('CRLF', "\r\n");
$postBody = '--'.$boundary.CRLF
. 'Content-Disposition: form-data; name="mediaItem[type]"'.CRLF
. 'Content-Type: application/json; charset=UTF-8'.CRLF
. CRLF
. 'image'.CRLF
. '--'.$boundary.CRLF
. 'Content-Disposition: form-data; name="photo"; filename="photo.png"'.CRLF
. 'Content-Type: image/png'.CRLF
. 'Content-Transfer-Encoding: binary'.CRLF
. CRLF
. file_get_contents($imagePath).CRLF
. '--'.$boundary.CRLF;
$context = stream_context_create(array(
'http' => array(
'method' => $request->get_normalized_http_method(),
'header' => array(
$request->to_header(),
'Content-Type: multipart/form-data; boundary='.$boundary,
),
'content' => $postBody,
'ignore_errors' => true,
),
));
echo file_get_contents($request->to_url(), false, $context);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment