dopmgo4707 2015-05-20 07:37
浏览 53

使用PHP cURL将图像发布到Twitter

I found that the same question is already asked in this link. But no proper solution I found for my problem.

I am trying to post an image to twitter using cURL. I can post the text but the image requires media[] parameter to be attached and Content-type=multipart/form-data. How do I do this? I tried the below code : but it returns with "Bad authentication data error".

Code:

<?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);

?>

How to attach media parameter here ? thank you for any help.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 matlab(相关搜索:紧聚焦)
    • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
    • ¥15 路易威登官网 里边的参数逆向
    • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
    • ¥50 需求一个up主付费课程
    • ¥20 模型在y分布之外的数据上预测能力不好如何解决
    • ¥15 processing提取音乐节奏
    • ¥15 gg加速器加速游戏时,提示不是x86架构
    • ¥15 python按要求编写程序
    • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入