【问题标题】:How to Upload Picture to Twitter Using Oauth, API , JSON and PHP, Help Required如何使用 Oauth、API、JSON 和 PHP 将图片上传到 Twitter,需要帮助
【发布时间】:2012-03-17 16:13:20
【问题描述】:

我对 twitter api 非常陌生,今天是我人生中第一次注册 twitter api。我的目标是在推特上发布我网站上的图片和一条消息。我已经从 Internet 下载了它当前的库,它给了我以下 2 个文件和一些示例。

我已经包含了这两个文件并得到了这个代码 photo_tweet.php 表示带有照片的推文

这是我的代码

<?php
require 'tmhOAuth.php';
require 'tmhUtilities.php';

$tmhOAuth = new tmhOAuth(array(
  'consumer_key'    => 'ZlhOWeCWG2MS5Wxxxxxx',
  'consumer_secret' => 'DIPjoKcIWjpGWmw5jGJSKGAOLxxxxxx',
  'user_token'      => 'xxxxx-OGtPyRSUOUaR6XQRLAFVuv14xxxxxx',
  'user_secret'     => 'xxxxxoimsrNFhlz7mPa9h5pyVSjxxxxxxx',
));

// we're using a hardcoded image path here. You can easily replace this with
// an uploaded image - see images.php in the examples folder for how to do this
// 'image = "@{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}",

// this is the jpeg file to upload. It should be in the same directory as this file.
$image = 'a.jpg';

$code = $tmhOAuth->request(
  'POST',
  'https://upload.twitter.com/1/statuses/update_with_media.json',
  array(
    'media[]'  => "@{$image};type=image/jpeg;filename={$image}",
    'status'   => 'Picture time',
  ),
  true, // use auth
  true  // multipart
);

if ($code == 200) {
  tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
} else {
  tmhUtilities::pr($tmhOAuth->response['response']);
}

?>

a.jpg 在我的服务器上。

这是我在推特上的设置!

请求类型:GET 请求 URI:* https://api.twitter.com/1/

当我上传所有这些代码并访问我的代码时,它返回空白屏幕,当我回显 $code;它返回 0

这就是我所观察和经历的一切。我需要你的帮助。我会非常非常感谢你

注意:事件当我删除我的消费者密钥和消费者密码时,此代码不会显示任何错误。只是一个空白屏幕。我希望它在出现任何问题但没有错误时显示错误


这是状态代码,只对我有用

$consumerKey = $consumer_key;
$consumerSecret = $consumer_secret;
$OAuthToken = $user_token;
$OAuthSecret = $user_secret;

include "OAuth.php";
include "twitteroauth.php";

$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $OAuthToken, $OAuthSecret);

$image = 'a.jpg';

$optsArray['status'] = 'Hi';



if (isset($_GET['msg'])) {
    $tweetmsg = $_GET['msg'];
    $tweet->post('statuses/update',$optsArray);

   if($tweet)
     echo "Your message has been sent to Twitter.";
   else
     echo "Your message has not been sent to Twitter.";

} else {
    echo "Your message has not been sent to Twitter.";
}

但它只在我使用时发布状态

update_with_media.json

$optsArray['@media[]'] = "@{$image}";

它不起作用,请帮我解决这个问题

【问题讨论】:

  • 你试过推特发简单的信息吗?我建议您先发布一条简单的消息来测试您的代码/api 密钥/令牌
  • 我使用另一个简单的代码进行测试,但它也给出了空白屏幕。我已经从 twitter 设置中正确复制了我的密钥和令牌。

标签: php json twitter jsonp twitter-oauth


【解决方案1】:

您可能想查看这篇文章。它会引导您完成这些步骤并提供许多示例。

API 提供以下方法。 twitpic logo 使用 PHP 在 twitpic API 上发布图片

METHOD: uploadAndPost (http://twitpic.com/api/uploadAndPost)
METHOD: upload (http://twitpic.com/api/upload)
Error codes
    1001 – Invalid twitter username or password
    1002 – Image not found
    1003 – Invalid image type
    1004 – Image larger than 4MB

以上是来自 twitpic 的 API 页面的 API 描述。但是你不需要进入那些复杂的细节。相反,您可以使用一个类,它可以让您在 twitpic 上发布图片并在同一帐户上更新您的 Twitter 状态。这是简单易用的。查看下面的代码。

<?php
class twitpic
{
  /* 
   * variable declarations
   */
  var $post_url='http://twitpic.com/api/upload';
  var $post_tweet_url='http://twitpic.com/api/uploadAndPost';
  var $url='';
  var $post_data='';
  var $result='';
  var $tweet='';
  var $return='';

/*
* @param1 is the array of data which is to be uploaded
* @param2 if passed true will display result in the XML format, default is false
* @param3 if passed true will update status twitter,default is false
*/

  function __construct($data,$return=false,$tweet=false)
  {
    $this->post_data=$data;
    if(empty($this->post_data) || !is_array($this->post_data)) //validates the data
      $this->throw_error(0);
    $this->display=$return;
    $this->tweet=$tweet;

  }

  function post()
  {
    $this->url=($this->tweet)?$this->post_tweet_url:$this->post_url; //assigns URL for curl request based on the nature of request by user
    $this->makeCurl();
  }
  private function makeCurl()
  {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($curl, CURLOPT_URL, $this->url);
    curl_setopt($curl, CURLOPT_POST, 3);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $this->post_data);
    $this->result = curl_exec($curl);
    curl_close($curl);
    if($this->display)
    {
      header ("content-type: text/xml");
      echo $this->result ;
    }

  }
  private function throw_error($code) //handles few errors, you can add more

  {
    switch($code)
    {
      case 0:
        echo 'Think, you forgot to pass the data';
        break;
      default:
        echo 'Something just broke !!';
        break;
    }
    exit;
  }
} //class ends here

?>

上面的 PHP 类完成了在 twitpic 上上传图片和在 twitter 上发布状态的所有技巧。您可以将此类与 HTML 表单或 PHP 脚本一起使用,以自动上传图像并发布推文。您可以结合使用以下HTML表单和PHP脚本来上传图片 来自用户的输入。

// This block of code should be written above the HTML and it will exit after the picture has been uploaded. If //you have turned display on (by passing 3rd param as true) then it will display the success message.
if($_POST)
{

  $file=$_FILES['media'];
  $postfields = array();

  $postfields['username'] = $_POST['username'];

  $postfields['password'] = $_POST['password'];
  $postfields['message'] = $_POST['message'];
  $postfields['media'] = "@$file[tmp_name]";

  $t=new twitpic($postfields,true,true);
  $t->post();
  exit;
}

<style type="text/javascript">
  *{font-family:verdana;}
  span{font-size:12px;color:#393939;}
  h3{font-size:14px;color:#5AAAF7;}
</style>
<body>

  <h3>Upload your pic to twitpic, and post status on twitter</h3>
  <form method="post"  enctype="multipart/form-data" action="<?= $_SERVER[PHP_SELF] ?>"   >
    <p><span style="height:40px;font-weight:bold;margin-right:56px;">Twitter Username :</span><input type="text" name="username" /></p>
    <p><span style="height:40px;font-weight:bold;margin-right:61px;">Twitter Password:</span><input type="password" name="password" /></p>

    <p><span style="vertical-align:text-top;height:40px;font-weight:bold;margin-right:28px;">Message to be posted :</span> <textarea cols="35" rows="2" name="message"></textarea></p>
    <p><span style="vertical-align:text-top;height:40px;font-weight:bold;">Choose an image to upload: </span><input type="file" name="media" /></p>
    <p style="width:250px;text-align:right;margin-top:50px;"><input type="submit" value="Upload&nbsp;&raquo;" /> </p>
  </form>
  <sup>Script powered by <a href="http://www.digimantra.com/">www.digimantra.com</a></sup>
</body>

You can skip posting update to twitter by passing the third argument as false or just by skipping it. If you want to upload image programmatically, without the user input or the form then you can do it using the following code. Make sure the image path is correctly mention, else it will throw an error.

<?php
$file='file_to_be_uploaded.gif';
$postfields = array();

$postfields['username'] = 'twitter_username';

$postfields['password'] = 'twitter_password';
$postfields['message'] = 'Message to be posted' ;
$postfields['media'] = "@$file"; //Be sure to prefix @, else it wont upload

$t=new twitpic($postfields,true,true);
$t->post();
?>

上面的这个类以二进制格式发布图像,如使用 curl php 发送二进制数据中所述。您可以更改课程以满足您的需要,也可以按照您喜欢的方式对其进行增强。希望这篇文章能帮助你学到一些东西。

【讨论】:

  • 感谢您的友好回复,上面的代码完美运行。但它需要输入用户名和密码。我想使用 Oauth。例如,如果用户访问我的网站,他喜欢一张图片,他可以将这张图片分享到 Twitter,而无需在我的网站上提供他的用户名和密码。使用 twitter API Oauth,
  • 事件当我删除我的消费者密钥和消费者密码以及其他详细信息时,此代码不会显示任何错误。只是一个空白屏幕。我希望它在出现任何问题但没有错误时显示错误
  • 不工作。错误 当我在登录页面上复制相同的用户名和密码以登录 twitter 时,它工作正常。 :(
猜你喜欢
  • 1970-01-01
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 2013-06-16
  • 2020-09-11
  • 2011-07-19
  • 2012-06-01
  • 1970-01-01
相关资源
最近更新 更多