使用PHP cURL将图像发布到Twitter

时间:2015-05-20 07:37:55

标签: php curl twitter

我发现在this link中已经提出了相同的问题。但是我找不到适合我问题的解决办法。

我正在尝试使用cURL将图片发布到twitter。我可以发布文字,但图片需要附加media []参数和Content-type=multipart/form-data。我该怎么做呢?我尝试了以下代码:但它返回“错误的身份验证数据错误”。

代码:

<?php
  $twitter_consumer_key = 'xxx';
  $twitter_consumer_secret = 'xxx';
  $twitter_access_token = 'xxx';
  $twitter_access_token_secret = 'xxx';
  $twitter_version = '1.0';
  $sign_method = 'HMAC-SHA1';

  $status='Image post';
  $file='image.jpg';
  $postdata = array("file[]" => realpath($file));
  $url = "https://api.twitter.com/1.1/statuses/update.json";
  $param_string = 'oauth_consumer_key=' . $this->twitter_consumer_key .
    '&oauth_nonce=' . time() .
    '&oauth_signature_method=' . $this->sign_method .
    '&oauth_timestamp=' . time() .
    '&oauth_token=' . $this->twitter_access_token .
    '&oauth_version=' . $this->twitter_version .
    '&status=' . rawurlencode($status);

  //Generate a signature base string for POST
  $base_string = 'POST&' . rawurlencode($url) . '&' . rawurlencode($param_string);
  $sign_key = rawurlencode($this->twitter_consumer_secret) . '&' . rawurlencode($this->twitter_access_token_secret);
  //Generate a unique signature
  $signature = base64_encode(hash_hmac('sha1', $base_string, $sign_key, true));
  $curl_header = 'OAuth oauth_consumer_key=' . rawurlencode($this->twitter_consumer_key) . ',' .
    'oauth_nonce=' . rawurlencode(time()) . ',' .
    'oauth_signature=' . rawurlencode($signature) . ',' .
    'oauth_signature_method=' . $this->sign_method . ',' .
    'oauth_timestamp=' . rawurlencode(time()) . ',' .
    'oauth_token=' . rawurlencode($this->twitter_access_token) . ',' . 'oauth_version=' . $this->twitter_version;

  $ch = curl_init();
  //Twitter post
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$curl_header . "Content-Type: multipart/form-data"));
  curl_setopt($ch, CURLOPT_VERBOSE, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, array('status=' .rawurlencode($status), 'media[]=' . $postdata));
  curl_setopt($ch, CURLOPT_URL, $url);

  $twitter_post = json_decode(curl_exec($ch));
  curl_close($ch);
  print_r($twitter_post);

?>

如何在此处附加媒体参数?谢谢你的帮助。

0 个答案:

没有答案