I found that the same question is already asked in this link. But no proper solution I found for my problem.
I am trying to post an image to twitter using cURL. I can post the text but the image requires media[] parameter to be attached and Content-type=multipart/form-data
. How do I do this? I tried the below code : but it returns with "Bad authentication data error".
Code:
<?php
$twitter_consumer_key = 'xxx';
$twitter_consumer_secret = 'xxx';
$twitter_access_token = 'xxx';
$twitter_access_token_secret = 'xxx';
$twitter_version = '1.0';
$sign_method = 'HMAC-SHA1';
$status='Image post';
$file='image.jpg';
$postdata = array("file[]" => realpath($file));
$url = "https://api.twitter.com/1.1/statuses/update.json";
$param_string = 'oauth_consumer_key=' . $this->twitter_consumer_key .
'&oauth_nonce=' . time() .
'&oauth_signature_method=' . $this->sign_method .
'&oauth_timestamp=' . time() .
'&oauth_token=' . $this->twitter_access_token .
'&oauth_version=' . $this->twitter_version .
'&status=' . rawurlencode($status);
//Generate a signature base string for POST
$base_string = 'POST&' . rawurlencode($url) . '&' . rawurlencode($param_string);
$sign_key = rawurlencode($this->twitter_consumer_secret) . '&' . rawurlencode($this->twitter_access_token_secret);
//Generate a unique signature
$signature = base64_encode(hash_hmac('sha1', $base_string, $sign_key, true));
$curl_header = 'OAuth oauth_consumer_key=' . rawurlencode($this->twitter_consumer_key) . ',' .
'oauth_nonce=' . rawurlencode(time()) . ',' .
'oauth_signature=' . rawurlencode($signature) . ',' .
'oauth_signature_method=' . $this->sign_method . ',' .
'oauth_timestamp=' . rawurlencode(time()) . ',' .
'oauth_token=' . rawurlencode($this->twitter_access_token) . ',' . 'oauth_version=' . $this->twitter_version;
$ch = curl_init();
//Twitter post
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$curl_header . "Content-Type: multipart/form-data"));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('status=' .rawurlencode($status), 'media[]=' . $postdata));
curl_setopt($ch, CURLOPT_URL, $url);
$twitter_post = json_decode(curl_exec($ch));
curl_close($ch);
print_r($twitter_post);
?>
How to attach media parameter here ? thank you for any help.