使用 PHP 在 Twitter 上上传图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9823169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:42:46  来源:igfitidea点击:

Upload Images On Twitter Using PHP

phpweb-servicestwittertwitter-oauth

提问by Tony Stark

How i can upload image on Twitter Wallusing consumer_keyand consumer_secretwithout login using PHP?

如何在Twitter Wall使用consumer_keyconsumer_secret不使用 PHP 登录时上传图像?

Please help me & thanks a lot.

请帮助我并非常感谢。

回答by Tony Stark

Well I get the answer, Download Twitter Apifor php & created one function.

好吧,我得到了答案,为 php下载Twitter Api并创建了一个函数。

function image_upload(){    

    define( 'YOUR_CONSUMER_KEY' , 'your twitter app consumer key');
    define( 'YOUR_CONSUMER_SECRET' , 'your twitter app consumer key secret');

    require ('twitt/tmhOAuth.php');
    require ('twitt/tmhUtilities.php');

    $tmhOAuth = new tmhOAuth(array(
             'consumer_key'    => "YOUR_CONSUMER_KEY",
             'consumer_secret' => "YOUR_CONSUMER_SECRET",
             'user_token'      => "YOUR_OAUTH_TOKEN",
             'user_secret'     => "YOUR_OAUTH_TOKEN_SECRET",
    ));

    $image = 'image.jpg';

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

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

回答by Artjom Kurapov

Well your user has to be authorized with OAuth with your APP,then you use API to post tweet. According to POST statuses/update& POST statuses/update_with_media, but I had trouble posting image (about a year ago, they probably fixed it by now).

那么您的用户必须通过您的 APP 获得 OAuth 授权,然后您使用 API 发布推文。根据POST statuses/update& POST statuses/update_with_media,但我在发布图片时遇到了麻烦(大约一年前,他们现在可能已经修复了)。

回答by matrim_c

You can use Oauthto authorise you app. I found thisguide helpful, as it shows how to connect to the API, and how to post on twitter. Using update_with_media should allow you to post with images

您可以使用Oauth授权您的应用程序。我发现指南很有帮助,因为它展示了如何连接到 API,以及如何在 twitter 上发帖。使用 update_with_media 应该允许您发布图像

回答by hugsbrugs

update_with_media is deprecated, you should consider using the following approach : https://dev.twitter.com/rest/public/uploading-media

update_with_media 已弃用,您应该考虑使用以下方法:https: //dev.twitter.com/rest/public/uploading-media

Using the excellent hybridauthlibrary and updating Twitter.php setUserStatus function with the following, you can achieve what you want :

使用优秀的hybridauth库并使用以下更新 Twitter.php setUserStatus 函数,您可以实现您想要的:

/**
* update user status
* https://dev.twitter.com/rest/public/uploading-media-multiple-photos
*/ 
function setUserStatus( $status )
{
    if(is_array($status))
    {
        $message = $status["message"];
        $image_path = $status["image_path"];
    }
    else
    {
        $message = $status;
        $image_path = null;
    }

    $media_id = null;

    # https://dev.twitter.com/rest/reference/get/help/configuration
    $twitter_photo_size_limit = 3145728;

    if($image_path!==null)
    {
        if(file_exists($image_path))
        {
            if(filesize($image_path) < $twitter_photo_size_limit)
            {
                # Backup base_url
                $original_base_url = $this->api->api_base_url;

                # Need to change base_url for uploading media
                $this->api->api_base_url = "https://upload.twitter.com/1.1/";

                # Call Twitter API media/upload.json
                $parameters = array('media' => base64_encode(file_get_contents($image_path)) );
                $response  = $this->api->post( 'media/upload.json', $parameters ); 
                error_log("Twitter upload response : ".print_r($response, true));

                # Restore base_url
                $this->api->api_base_url = $original_base_url;

                # Retrieve media_id from response
                if(isset($response->media_id))
                {
                    $media_id = $response->media_id;
                    error_log("Twitter media_id : ".$media_id);
                }

            }
            else
            {
                error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
            }
        }
        else
        {
            error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
        }
    }

    if($media_id!==null)
    {
        $parameters = array( 'status' => $message, 'media_ids' => $media_id );
    }
    else
    {
        $parameters = array( 'status' => $message); 
    }
    $response  = $this->api->post( 'statuses/update.json', $parameters );

    // check the last HTTP status code returned
    if ( $this->api->http_code != 200 ){
        throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
    }
}

Just using it like so :

就像这样使用它:

$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );

$twitter_status = array(
    "message" => "Hi there! this is just a random update to test some stuff",
    "image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );

Or for a full text twitt :

或全文推特:

$res = $adapter->setUserStatus( "Just text" );