上传图片PHP到twitter(api)

时间:2013-05-31 16:47:13

标签: php html api twitter upload

我是PHP新手,所以请保持简单^^ ..

我尝试使用api将图像上传到twitter。

当文件在我的服务器上时,我已经可以将图像发布到twitter(test.jpg),但用户必须能够将其直接上传到twitter ...

我该怎么做?

我在'tweet.html'

中有这段代码
<form action="photo_tweet.php" method="post">
    <p>tweet: <input type="text" name="tweet" /></p>
    <input type="file" name="image" id="image"/>
    <input type="submit" name="submit" value="Submit" />
</form>

我在'photo_tweet.php'

中有这段代码
<?php

/**
 */

require '../tmhOAuth.php';
require '../tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
  'consumer_key'    => 'xxxxxxxxxxxxxx',
  'consumer_secret' => 'xxxxxxxxxxxxxx',
  'user_token'      => 'xxxxxxxxxxxxxx',
  'user_secret'     => 'xxxxxxxxxxxxxx',
));

// 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.
    $tweetmessage = $_POST['tweet'];
    $image = 'test.jpg';

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

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

2 个答案:

答案 0 :(得分:1)

我在想Evert,这是你做这件事最简单的方法,如下。有一个上传图片页面。此页面TEMPORARILY将图像上传到您的服务器,因为它在上传到您的服务器后,会重定向到存储在变量中的图像的文件名。然后它动态上传到Twitter,5分钟后,从您的网站删除它。

主要观点:

  • 用户上传到您的网站
  • 重定向到您网站上的Twitter上传页面
  • 上传您之前的$ image
  • 然后,让它计时,以便在5分钟内从您的网站删除。

注意:

  • 如果您想拥有一个很棒的Twitter客户端,请保持上传的所有图片。更好的安全性。
  • 此外,我不知道您是否知道,但如果您的Twitter客户端发布了一个.jpg的直接链接,它将与pic.twitter.com上的图像相同。
  • 最后,我认为你掌握了它,但作为一个初学的PHP开发人员,我建议你选择一个较小的项目;)
祝你好运! Lakota Lustig

答案 1 :(得分:0)

如果你想先绕过上传到你服务器的图像,那么你需要使用他们的javascript api,如果他们有一个允许通过它发布图像。

否则它会在评论中告诉你如何做到这一点。

// 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']}",

$_FILES是全局变量,用于保存用户通过推文表单提交的上传图像的信息。