[PHP]curlを使わずにtwitterに投稿する

twitter APIにアクセスするためのPHP製ライブラリとしては、codebirdtwitteroauthなどありますが、大抵はcurl系の関数を使っています。

ただ、curl系の関数は必ず使えるわけではなく、コンパイルオプションを指定したり、PHP 5.5以降ではPECLからインストールしたりする必要があります。

一方、PHPには、組み込みでリクエストの送信を行える関数が存在します。file_get_contents()です(fopen()でもおそらく可)。php.iniで「allow_url_fopen = On」と設定されていれば、file_get_contents()の第三引数にコンテキストリソースを渡すことで、HTTPリクエストを行うことができます。

なお、OAuthに関しては、処理が複雑なので、今回はライブラリ(oauth-php)を利用します。

<?php
require_once __DIR__ . '/OAuth.php';
// アプリケーションのコンシューマキー、アクセストークンを設定
$consumer_key = '';
$consumer_secret = '';
$access_token = '';
$access_secret = '';
// リクエストを行うURL
$url = 'https://api.twitter.com/1.1/statuses/update.json';
// 投稿は POST
$method = 'POST';
$tweet = 'ツイートテスト' . mt_rand(0, 100); // 同じツイートは繰り返せないので、後ろに乱数をくっつける(繰り返しのテストをやりやすくするため)
$parameters = array('status' => $tweet);
// OAuth関係の処理
$sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
$consumer = new OAuthConsumer($consumer_key, $consumer_secret);
$token = new OAuthConsumer($access_token, $access_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, $token, $method, $url, $parameters);
$request->sign_request($sha1_method, $consumer, $token);
$options = array(
'http'=>array(
'method'  => $request->get_normalized_http_method(),
'header'  => 'Content-Type: application/x-www-form-urlencoded',
'content' => $request->to_postdata()
)
);
$context = stream_context_create($options);
$result = file_get_contents($request->get_normalized_http_url(), false, $context); // ツイートを行う
$result = json_decode($result); // twitterから返ってきたJSON文字列を配列に変換
var_dump($result);

参考:OAuth.phpだけで twitter APIする
上記参考URLのスクリプトを参考に、(1) twitter APIのURLを最新版に修正 (2) リクエストのヘッダーにContent-Typeを追加 を行いました。

コメントをどうぞ

コメントを残す