Reputation: 344
I have a problem when trying to upload a photo to twitter. I use twitteroauth.php to authenticate, and I have no problem posting a tweet through the api, or receiving data. But when I want to upload a photo, i get the following error: {"errors":[{"message":"Could not authenticate you","code":32}]}
This is my code:
<?php
require_once('../include/initialize.php');
require_once('twitter/twitteroauth.php');
if(isset($_GET['access_token']) && $_GET['access_token'] != ''){
$accesstoken = $_GET['access_token'];
}else{
$accesstoken = TWITTER_ACCESS_TOKEN;
}
if(isset($_GET['access_token_secret']) && $_GET['access_token_secret'] != ''){
$accesstokensecret = $_GET['access_token_secret'];
}else{
$accesstokensecret = TWITTER_ACCESS_TOKEN_SECRET;
}
$consumerkey = TWITTER_CONSUMER_KEY;
$consumersecret = TWITTER_CONSUMER_SECRET;
$twitter = new TwitterOAuth($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$url = $_POST['url'];
$filename = $_POST['filename'];
// function to replace file_get_contents()
function file_get_the_contents($url) {
$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
// original script updated with new function
$imgget = file_get_the_contents($url);
$twitter_api = "https://upload.twitter.com/1.1/media/upload.json?media=".$imgget."&type=photo";
$twitter_img = $twitter->post($twitter_api);
echo json_encode($twitter_img);
Can anybody help me with this issue. I have looked around on forums, but all other issues I find are referring to the statuses/update_with_media which is deprecated. Thanks.
Upvotes: 4
Views: 1002
Reputation: 61
Per this answer by toster-cx, you need to make sure that you encode the image data in base 64. Otherwise, Twitter will respond with error 32. You will need something like this:
$imgget = base64_encode(file_get_the_contents($url));
Upvotes: 2