update_with_media using abraham's twitteroauth
Asked Answered
M

6

8

I'm trying to implement an upload_with_media request from ajax using Abraham's twitteroauth library (TwitterOAuth v0.2.0-beta2). I've had no problems with basic posts but when I try to include media I get this as a response:

"{"request":"\/1\/statuses\/update_with_media.json","error":"Error creating status."}"

My code for posting media looks like this:

   $image = $_FILES["media"]["tmp_name"];

    $parameters = array(
        'media[]'  => "@{$image};type=image/jpeg;filename={$image}",
        'status'   => $status
      );

    if(isset($reply_id)) {
        $parameters['in_reply_to_status_id'] = $reply_id;
    }
    $post = $twitteroauth->post('https://upload.twitter.com/1/statuses/update_with_media.json', $parameters);
    echo json_encode($post);

I have verified that all data is being sent to this script correctly and even managed to get an update_with_media post working using the same data above and the tmhOAuth library but as the rest of my widget uses twitteroauth, I'd prefer to keep things uniform. I've also tried it with and without the .json affixed to the ending and saw no difference. Can anyone show me an example of a successful implementation of update_with_media using twitteroauth? I can't seem to figure out what I'm doing wrong.

Mixup answered 10/5, 2012 at 8:42 Comment(2)
TwitterOAuth does not currently support media uploads. I hope to add support in the future.Dwaindwaine
@abraham, any idea when we expect support for media uploads? Also, what do you suggest to those who still want to upload media via their script?Seneca
T
5

After dealing during hours for a solution to UPDATE_WITH_MEDIA with twitteraouth library, I found the following solution that works fine:

  • First: the PHP original library linked from Twitter Dev here does not work.

IS NOT WORKING WITH UPDATE_WITH_MEDIA

The basic diference is that the original has the function "post" without "$multipart" parameter. This parameter is what allows to send what Twiiter ask for in the documentation: a multipart enctype post. So at the end the basic code is as follows:

$image_path="folder/image.jpg";

$handle = fopen($image_path,'rb');
$image  = fread($handle,filesize($image_path));
fclose($handle);

$params = array(
  'media[]' => "{$image};type=image/jpeg;filename={$image_path}",
  'status'  => "Put your message here, must be less than 117 characters!"
);
$post = $connection->post('statuses/update_with_media', $params, true);

IMPORTANT! If you try this code with the original library, you will find out an error. You have to download from the link above and replace both files (OAuth.php and twitteroauth.php) in your project.

Tilden answered 10/7, 2014 at 13:11 Comment(1)
Brilliant! Thank you, this worked for me too. Natefanaro's library unfortunately does not work with PHP 5.5+ due to CURLFile requirement. Your solution and the linked branch of the library are the only one of the options on this thread that worked for me. I'm also guessing fopen is a better way to handle the image as it should allow you to pull in a remote image too.Polonaise
F
4

Try using codebird-php https://github.com/mynetx/codebird-php

It turn out that it does the trick despite being last in the list of php libraries suggested by Twitter. Just grab codebird.php and cacert.pem from the git repo.

    include_once('codebird.php');
    \Codebird\Codebird::setConsumerKey($consumer_key, $consumer_secret);
    $cb = \Codebird\Codebird::getInstance();
    $cb->setToken($token, $token_secret);
    $status = 'Gamo, I just tweeted with an image!';
    $filename = '/home/asdf/test.png';
    $cb->statuses_updateWithMedia(array('status' => $status, 'media[]' => $filename));
Fracture answered 21/2, 2013 at 17:57 Comment(6)
After struggling for an hour to get the Abraham twitteroauth to do this, I found your answer and within 3 minutes had it working. Thanks!Systematize
I have been struggling with auto tweeting for days now. Now I found your code, it seems even simpler than any other and I still cant get it to work. I downloaded the codebird files (codebird.php and cacert.pem) declared key and token variables and changed $filename to point to an image on my server. It did not work :(Decadent
@ahojvole Sorry to hear that. I used this library a year ago. Maybe the author of codebird changed something. You should check with codebird's documentation.Fracture
@ahojvole What is cacert.pem that you mention?Fracture
@Fracture Its slightly embarrassing I cant say what the cacert.pem file is for, however codebird.php asks for this file (perhaps in later versions) without this file, not even text gets tweeted.Decadent
@ahojvole There are a few changes in the latest version of codebird. I updated my answer.Fracture
J
2

The original library doesn't include uploading media functionality yet. You may check out https://github.com/natefanaro/twitteroauth .

Jacklighter answered 7/11, 2013 at 12:35 Comment(1)
Unfortunately, this update to the library does not work with PHP 5.5 or higher.Polonaise
A
0

I suggest that you use Fiddler2 or some similar tool to examine and compare the messages that go out with twitteroauth, and also with tmhOAuth. You will see the difference.

In my experience, this is what an HTTP POST to Twitter looks like, using update_with_media.{xml,json}. The suffix you use affects only the respponse, I believe. (Your app must set the Authorization header in a way that is specific to your app.)

You want to get twitteroauth to post something like the following

POST https://upload.twitter.com/1/statuses/update_with_media.xml HTTP/1.1
Authorization: OAuth oauth_callback="oob", oauth_consumer_key="xxxxxxxxxxxx", oauth_nonce="7774328k", oauth_signature="pUYjRnccmrBYiO1j9cliETsw%2B5s%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1318300521", oauth_token="59152613-vrlZ2edX56PudQtBmpAWd3SPDt9cPyAhibO7ysl6W", oauth_version="1.0"
Content-Type: multipart/form-data; boundary=======c49479438c600bf59345e======
Host: upload.twitter.com
Content-Length: 7320
Connection: Keep-Alive

--======c49479438c600bf59345e======
Content-Disposition: form-data; name="status"

working on a Tweet tool that uses the OAuth Manager library.
--======c49479438c600bf59345e======
Content-Disposition: file; name="media[]"; filename="ThisIsAPicture.png"
Content-Type: image/png

  ...binary png data here...

--======c49479438c600bf59345e======--
Asperse answered 10/5, 2012 at 13:10 Comment(3)
dear @Asperse would you explain above lines.. where to put this code and how to run? Its above phpLotta
Those are messages. You want your code to generate those messages.You don't run it. That's the output.Asperse
#11244112 what problem with this? can you help me?Lotta
D
0

I want to sent url link with status param

like : Put you message here

Dumbhead answered 10/9, 2014 at 11:41 Comment(0)
P
0

For anyone reading this in 2022, I could not find the answer anywhere for this, but I managed to solve it by uploading media first WITHOUT setting api version to 2. But immediately after retrieving the image, then set the api version.

It seems that version 2 endpoints do not fully support media upload yet, don't know why. But this is what works perfectly for me, hope it's useful for someone:

$connection = new TwitterOAuth(env('TWITTER_CONSUMER_KEY'), env('TWITTER_CONSUMER_SECRET'), env('TWITTER_ACCESS_TOKEN'), env('TWITTER_ACCESS_TOKEN_SECRET'));

    $result = $connection->upload('media/upload', [
        'media' => '/img/path.png',
    ], true);

    // check here to see if img has uploaded
    var_dump($result);

    $connection->setApiVersion('2');

    $response = $connection->post('tweets', [
        'text' => 'Test',
        'media' => [
            'media_ids' => [$result->media_id_string],
        ]
    ], true);

    var_dump($response);
Paracasein answered 14/7, 2022 at 21:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.