POST media/upload - media type unrecognized

php

#1

Here is my PHP code to upload image on twitter:

$mediaContent = file_get_contents('/path/to/image');

$parameters = array(
			'media' => $mediaContent,
			'media_data' => base64_encode($mediaContent),
			);

$media = $connection->upload('media/upload', $parameters);

And, here I got response for above request:

stdClass Object
(
    [request] => /1.1/media/upload.json
    [error] => media type unrecognized.
)

#2

I have done it myself. Thanks for your support.


#3

Are you able to share the solution?


#4

I have created an “upload” function in “twitteroauth.php” file.

  function upload($url, $parameters = array())
  {
    $method = "POST";
    $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
    $request->sign_request($this->sha1_method, $this->consumer, $this->token);

    $response = $this->http($request->get_normalized_http_url(), $method, $request->to_postdata());
    if ($this->format === 'json' && $this->decode_json)
    {
      $response = json_decode($response);
    }
    return $response;
  }

Here, I call that function after twitter callback response.

$mediaContent = file_get_contents("relative/path/to/image");

$parameters = array(
	'media' => base64_encode($mediaContent),
);

$media1 = $connection->upload('https://upload.twitter.com/1.1/media/upload.json', parameters);

$parameters = array(
	'status' => $msg,
	'media_ids' => $media1->media_id_string
);

/* For normal post : $host = "https://api.twitter.com/1.1/"; already sets in "TwitterOAuth" class. So I am not sending full path in function */
$tweet = $connection->post('statuses/update', $parameters);

#5

Great! Glad you got it working, and thank you very much for sharing the solution :thumbsup:


#6