Upload Images On Twitter Using PHP
Asked Answered
P

4

6

How i can upload image on Twitter Wall using consumer_key and consumer_secret without login using PHP?

Please help me & thanks a lot.

Pappus answered 22/3, 2012 at 13:23 Comment(1)
Guys if this question helpful, you can upvote also not only answer...Pappus
P
9

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

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;
}
Pappus answered 26/3, 2012 at 13:40 Comment(9)
I had to add a $headers variable to the $tmhOAuth->request() call. I was getting back a 417 error from Twitter, and Googling led me to stick in array('Expect' => '') after the multipart true. It worked perfectly after that.Casuist
I used for iphone app, this is on app store & yes it is still working.Pappus
If some one facing problem to integrate the code or something else then write comment.Please don't give downvote!!!Pappus
I don´t get the DEFINE lines, there more than one Consumer Key ? Why there´s two fields ? ('YOUR_CONSUMER_KEY' , 'your twitter app consumer key') ?Killdeer
@Killdeer for twitter integration you need four things YOUR_CONSUMER_KEY","YOUR_CONSUMER_SECRET","YOUR_OAUTH_TOKEN","YOUR_OAUTH_TOKEN_SECRET".Pappus
where is twitt/tmhUtilities.php?Debris
returns error code 410 which means this code uses API v1 which is depricated, use v1.1Debris
Please consider updating the code as it isn't working any longer.Watchtower
NOTE:update_with_media API call is deprecated!Fabozzi
J
3

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).

Jotun answered 22/3, 2012 at 13:42 Comment(0)
P
2

You can use Oauth to authorise you app. I found this guide 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

Print answered 23/3, 2012 at 10:38 Comment(0)
F
1

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

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

/**
* 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" );
Fulani answered 16/11, 2014 at 10:48 Comment(1)
Just for guys like me stumbling on this one, media feature has been merged over a year ago ;-) github.com/hybridauth/hybridauth/blob/master/hybridauth/Hybrid/…Haygood

© 2022 - 2024 — McMap. All rights reserved.