I am trying to write a self-contained PHP script – no dependencies – to post tweets. I have managed it with just text, and I know how to include an uploaded image with a tweet. The problem is uploading the image in the first place. I’m getting no reply whatsoever from X.
I know uploading an image has to be done with the 1.1 API, so maybe the OAuth code (which works for v2 requests) is wrong in some way?
My test code attempts to send a Base64-encoded image (temp_twitter_image.jpg) that is on the server:
<?php
$consumerKey = 'SECRET';
$consumerSecret = 'SECRET';
$accessToken = 'SECRET';
$accessTokenSecret = 'SECRET';
$imgfn = "temp_twitter_image.jpg";
$u = 'https://api.twitter.com/1.1/media/upload.json';
$oauthTimestamp = time();
$oauthNonce = md5(uniqid(rand(), true));
$oauthParameters = array(
'oauth_consumer_key=' . $consumerKey,
'oauth_nonce=' . $oauthNonce,
'oauth_signature_method=HMAC-SHA1',
'oauth_timestamp=' . $oauthTimestamp,
'oauth_token=' . $accessToken,
'oauth_version=1.0'
);
sort($oauthParameters);
$oauthParameterString = implode('&', $oauthParameters);
$oauthBaseString = 'POST&';
$oauthBaseString .= urlencode($u) . '&';
$oauthBaseString .= urlencode($oauthParameterString);
$oauthSigningKey = urlencode($consumerSecret) . '&' . urlencode($accessTokenSecret);
$oauthSignature = base64_encode(hash_hmac('sha1', $oauthBaseString, $oauthSigningKey, true));
$oauthSignature = urlencode($oauthSignature);
$authorizationHeader = 'OAuth ';
$authorizationHeader .= 'oauth_consumer_key="' . $consumerKey . '", ';
$authorizationHeader .= 'oauth_nonce="' . $oauthNonce . '", ';
$authorizationHeader .= 'oauth_signature="' . $oauthSignature . '", ';
$authorizationHeader .= 'oauth_signature_method="HMAC-SHA1", ';
$authorizationHeader .= 'oauth_timestamp="' . $oauthTimestamp . '", ';
$authorizationHeader .= 'oauth_token="' . $accessToken . '", ';
$authorizationHeader .= 'oauth_version="1.0"';
$img = file_get_contents($imgfn);
$b64 = base64_encode($img);
//$postFields = '{ "media": "' . $b64 . '", "media_category":"TWEET_IMAGE" }';
$postFields = '{ "media": "' . $b64 . '}';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $u,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: ' . $authorizationHeader
),
));
$response = curl_exec($curl);
echo "curl executed<br>";
echo $response;
//$media_id = json_decode($response)->media_id;
curl_close($curl);
?>
If anyone can tell me what I’m doing wrong, I’d be grateful.
Seymour Clufley is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.