Posting image + status with the Twitter API using php

前端 未结 1 1565
无人共我
无人共我 2021-01-05 23:57

I ended up using codebird and not TwitterAPIExchange.php. Please see my answer.

TwitterAPIExchange.php

I am racking my brain trying to figure out why my code

相关标签:
1条回答
  • 2021-01-06 00:05

    I ended up not being able to use this method and found a more current solution. The one thing I learned about using php to tweet images with a message is that you have to load the image first up to twitter in which the API will return a media_id back to you. That media_id is associated with the image. Once you have the media_id back then you associate that ID with your message and send the message with the media_id's. That made the code make more sense once I learned that.

    I used codebird instead to achieve tweeting with php.

    All you have to do is create a function like so

    function tweet($message,$image) {
    
    // add the codebird library
    require_once('codebird/src/codebird.php');
    
    // note: consumerKey, consumerSecret, accessToken, and accessTokenSecret all come from your twitter app at https://apps.twitter.com/
    \Codebird\Codebird::setConsumerKey("Consumer-Key", "Consumer-Secret");
    $cb = \Codebird\Codebird::getInstance();
    $cb->setToken("Access-Token", "Access-Token-Secret");
    
    //build an array of images to send to twitter
    $reply = $cb->media_upload(array(
        'media' => $image
    ));
    //upload the file to your twitter account
    $mediaID = $reply->media_id_string;
    
    //build the data needed to send to twitter, including the tweet and the image id
    $params = array(
        'status' => $message,
        'media_ids' => $mediaID
    );
    //post the tweet with codebird
    $reply = $cb->statuses_update($params);
    
    }
    

    It's important when you download the API you make sure that cacert.pem is located in the same directory as codebird.php which comes with the download. Don't just download codebird.php

    Also keep in mind Twitter's guidelines for images and videos relating to sizes and parameters.

    Make sure you have at least php version 5.3 and curl enabled on your server. If you are not sure what you have you can create any .php file and add phpinfo(); and that will tell you everything that your php config has.

    Once you have that all in place then all you have to do to send a tweet with codebird is

    tweet('This is my sample tweet message','http://www.example.com/image.jpg');
    
    0 讨论(0)
提交回复
热议问题