Upload Images On Twitter Using PHP
Well I get the answer, Download Twitter Api for php & created one function.
function image_upload(){
define( 'YOUR_CONSUMER_KEY' , 'your twitter app consumer key');
define( 'YOUR_CONSUMER_SECRET' , 'your twitter app consumer key secret');
require ('twitt/tmhOAuth.php');
require ('twitt/tmhUtilities.php');
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => "YOUR_CONSUMER_KEY",
'consumer_secret' => "YOUR_CONSUMER_SECRET",
'user_token' => "YOUR_OAUTH_TOKEN",
'user_secret' => "YOUR_OAUTH_TOKEN_SECRET",
));
$image = 'image.jpg';
$code = $tmhOAuth->request( 'POST','https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "@{$image};type=image/jpeg;filename={$image}",
'status' => 'message text written here',
),
true, // use auth
true // multipart
);
if ($code == 200){
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
}else{
tmhUtilities::pr($tmhOAuth->response['response']);
}
return tmhUtilities;
}
Posting image + status with the Twitter API using php
I ended up not being able to use this method and found a more current solution. The one thing I learned about using php to tweet images with a message is that you have to load the image first up to twitter in which the API will return a media_id
back to you. That media_id
is associated with the image. Once you have the media_id
back then you associate that ID with your message and send the message with the media_id
's. That made the code make more sense once I learned that.
I used codebird instead to achieve tweeting with php.
All you have to do is create a function like so
function tweet($message,$image) {
// add the codebird library
require_once('codebird/src/codebird.php');
// note: consumerKey, consumerSecret, accessToken, and accessTokenSecret all come from your twitter app at https://apps.twitter.com/
\Codebird\Codebird::setConsumerKey("Consumer-Key", "Consumer-Secret");
$cb = \Codebird\Codebird::getInstance();
$cb->setToken("Access-Token", "Access-Token-Secret");
//build an array of images to send to twitter
$reply = $cb->media_upload(array(
'media' => $image
));
//upload the file to your twitter account
$mediaID = $reply->media_id_string;
//build the data needed to send to twitter, including the tweet and the image id
$params = array(
'status' => $message,
'media_ids' => $mediaID
);
//post the tweet with codebird
$reply = $cb->statuses_update($params);
}
It's important when you download the API you make sure that cacert.pem
is located in the same directory as codebird.php
which comes with the download. Don't just download codebird.php
Also keep in mind Twitter's guidelines for images and videos relating to sizes and parameters.
Make sure you have at least php version 5.3 and curl enabled on your server. If you are not sure what you have you can create any .php
file and add phpinfo();
and that will tell you everything that your php config has.
Once you have that all in place then all you have to do to send a tweet with codebird is
tweet('This is my sample tweet message','http://www.example.com/image.jpg');
PHP - Post Media / Image to twitter
Seems that you should upload your media first (after creating TwitterOAuth object)
$media = $tweet->upload('media/upload', array('media' => 'path_to_your_file'));
Then set the parameters of your tweet (like status and media)
$parameters = array(
'status' => 'Your Tweet status',
'media_ids' => $media->media_id_string);
You can view the docs to upload up to 4 media resources in the same tweet
And then send the tweet with the parameters.
$send_tweet = $connection->post('statuses/update', $parameters);
You can see an example using media here: https://twitteroauth.com/
And the statuses/update reference here: https://dev.twitter.com/rest/reference/post/statuses/update
How to Upload Picture to Twitter Using Oauth, API , JSON and PHP, Help Required
You might want to check this article out. It walks you through the steps and gives many examples.
The following methods are provided by the API.
twitpic logo Post pictures on twitpic API using PHP
METHOD: uploadAndPost (http://twitpic.com/api/uploadAndPost)
METHOD: upload (http://twitpic.com/api/upload)
Error codes
1001 – Invalid twitter username or password
1002 – Image not found
1003 – Invalid image type
1004 – Image larger than 4MB
Given above is the API description from twitpic’s API page. But you need not to get into those complicated details. Instead you can use a class which will let you post a picture on twitpic and update your twitter status on the same account. This is simple & easy to use. Check out the code below.
<?php
class twitpic
{
/*
* variable declarations
*/
var $post_url='http://twitpic.com/api/upload';
var $post_tweet_url='http://twitpic.com/api/uploadAndPost';
var $url='';
var $post_data='';
var $result='';
var $tweet='';
var $return='';
/*
* @param1 is the array of data which is to be uploaded
* @param2 if passed true will display result in the XML format, default is false
* @param3 if passed true will update status twitter,default is false
*/
function __construct($data,$return=false,$tweet=false)
{
$this->post_data=$data;
if(empty($this->post_data) || !is_array($this->post_data)) //validates the data
$this->throw_error(0);
$this->display=$return;
$this->tweet=$tweet;
}
function post()
{
$this->url=($this->tweet)?$this->post_tweet_url:$this->post_url; //assigns URL for curl request based on the nature of request by user
$this->makeCurl();
}
private function makeCurl()
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $this->url);
curl_setopt($curl, CURLOPT_POST, 3);
curl_setopt($curl, CURLOPT_POSTFIELDS, $this->post_data);
$this->result = curl_exec($curl);
curl_close($curl);
if($this->display)
{
header ("content-type: text/xml");
echo $this->result ;
}
}
private function throw_error($code) //handles few errors, you can add more
{
switch($code)
{
case 0:
echo 'Think, you forgot to pass the data';
break;
default:
echo 'Something just broke !!';
break;
}
exit;
}
} //class ends here
?>
The above PHP class does all the trick to upload picture on twitpic and post status on the twitter. You can use this class with both using HTML form or using a PHP script to automatically upload the image and post the tweet. You can use the following HTML form and PHP script in combination to upload picture by taking
input from the user.
// This block of code should be written above the HTML and it will exit after the picture has been uploaded. If //you have turned display on (by passing 3rd param as true) then it will display the success message.
if($_POST)
{
$file=$_FILES['media'];
$postfields = array();
$postfields['username'] = $_POST['username'];
$postfields['password'] = $_POST['password'];
$postfields['message'] = $_POST['message'];
$postfields['media'] = "@$file[tmp_name]";
$t=new twitpic($postfields,true,true);
$t->post();
exit;
}
<style type="text/javascript">
*{font-family:verdana;}
span{font-size:12px;color:#393939;}
h3{font-size:14px;color:#5AAAF7;}
</style>
<body>
<h3>Upload your pic to twitpic, and post status on twitter</h3>
<form method="post" enctype="multipart/form-data" action="<?= $_SERVER[PHP_SELF] ?>" >
<p><span style="height:40px;font-weight:bold;margin-right:56px;">Twitter Username :</span><input type="text" name="username" /></p>
<p><span style="height:40px;font-weight:bold;margin-right:61px;">Twitter Password:</span><input type="password" name="password" /></p>
<p><span style="vertical-align:text-top;height:40px;font-weight:bold;margin-right:28px;">Message to be posted :</span> <textarea cols="35" rows="2" name="message"></textarea></p>
<p><span style="vertical-align:text-top;height:40px;font-weight:bold;">Choose an image to upload: </span><input type="file" name="media" /></p>
<p style="width:250px;text-align:right;margin-top:50px;"><input type="submit" value="Upload »" /> </p>
</form>
<sup>Script powered by <a href="http://www.digimantra.com/">www.digimantra.com</a></sup>
</body>
You can skip posting update to twitter by passing the third argument as false or just by skipping it. If you want to upload image programmatically, without the user input or the form then you can do it using the following code. Make sure the image path is correctly mention, else it will throw an error.
<?php
$file='file_to_be_uploaded.gif';
$postfields = array();
$postfields['username'] = 'twitter_username';
$postfields['password'] = 'twitter_password';
$postfields['message'] = 'Message to be posted' ;
$postfields['media'] = "@$file"; //Be sure to prefix @, else it wont upload
$t=new twitpic($postfields,true,true);
$t->post();
?>
This above class posts the image in the binary format as discussed in Send binary data using curl php. You can change the class to suit your need and you can also enhance it the way you like. Hope this post helped you learn something.
Related Topics
The Requested Url /Projectname/Users Was Not Found on This Server. Laravel
Secure and Flexible Cross-Domain Sessions
How to? Form Post to Multiple Locations
Eloquent Many-To-Many-To-Many - How to Load Distant Relation Easily
How to Consume a Wcf Web Service That Uses Custom Username Validation with a PHP Page
How to Use Curl and PHP Simple HTML Dom Parser with Object
Error 405 (Method Not Allowed) Laravel 5
Uncompress a Gzip File from Curl, on PHP
How to Get Array Key from Corresponding Array Value
Php: Date Larger Than Current Date
Utf-8 Special Characters Not Displaying
Escaping Column Names in Pdo Statements
PHP Directory List from Remote Server
PHP Datetime Createfromformat Functionality