Search code examples
phptwitter

Why I cannot post image through twitter API?


This is my code, I am trying to post tweet with image, but only text get posted? I really really want to post image as well. I am pulling my hair out for that, HELP!

<?php
error_reporting(E_ALL);
require_once('TwitterAPIExchange.php');
//echo 'start';
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
require_once('connect.php');
$recid=$_GET['recid'];
//echo $recid;

$dsn='mysql:host='.$hostname.';dbname=twitter_db';
try{
    $dbh=new PDO($dsn,$username,$password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $stmt=$dbh->prepare("SELECT * FROM gr_twitter WHERE recid=:recid");
    $stmt->execute(array(
                    'recid'=>$recid
                    ));
    $foundResult=$stmt->fetchAll();
    $tweetmsg=$foundResult[0]['tweet'];
    $tweetImage=$foundResult[0]['tweetImageName'];
    $timestamp=$foundResult[0]['sentTimestamp'];

    print_r($foundResult);
    $stmt2=$dbh->prepare("UPDATE gr_twitter SET sent=1 WHERE recid=:recid");
    $stmt2->execute(array(
                    'recid'=>$recid
                    ));
    }
catch(PDOException $e){}
// Perform a GET request and echo the response **/
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/statuses/update.json';
$requestMethod='POST';

////images is stored in D:\Databases\RC_Data_FMS\images\Files\images\tweetImage folder

    $tweetImage='D:\Databases\RC_Data_FMS\images\Files\images\tweetImage/images.jpg';
        $postfields = array(
            'status' => $tweetmsg,
            'media' => "@{$tweetImage}"
            
        );
/** POST fields required by the URL above. See relevant docs as above **/
//print_r($postfields).'<br />';
            $twitter = new TwitterAPIExchange($Yh_settings);
  $response=  $twitter->buildOauth($url, $requestMethod)
                    ->setPostfields($postfields)
                    ->performRequest();

            echo "Success, you just tweeted!<br />";

        
var_dump(json_decode($response));
//////////////////////////////////////////////////////////////////////////
function objectToArray($d) 
{
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
        $d = get_object_vars($d);
    }

    if (is_array($d)) {
        /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
       // return array_map(__FUNCTION__, $d);
    } else {
        // Return array
       // return $d;
    }
}


?>

Solution

  • I recommend you to use tmhOAuth library if you want to post images that are located in your server.

    Here you have an example:

    <?php
    
    require_once('./tmhOAuth.php');
    
    $tmhOAuth = new tmhOAuth(array(
        'consumer_key'    => CONSUMER_KEY,
        'consumer_secret' => CONSUMER_SECRET,
        'user_token'      => OAUTH_TOKEN,
        'user_secret'     => OAUTH_TOKEN_SECRET
    ));
    
    $tweetText = 'Your text here';
    $imageName = 'picture.png';
    $imagePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . $imageName;
    
    $code = $tmhOAuth->request(
        'POST',
        $tmhOAuth->url('1.1/statuses/update_with_media'),
        array(
            'media[]'  => "@{$imagePath};type=image/png;filename={$imageName}",
            'status'   => $tweetText
        ),
        true, // use auth
        true  // multipart
    );
    
    ?>
    

    Hope this helps!