Post to Twitter From a PHP Script
April 5th, 2009 by MattIf you’ve used Twitter for long, you’re probably aware of their impressive API. Nearly any day-to-day task that you can perform on Twitter.com can be done programmatically via the API. (This enables us to have useful applications like Twhirl.)
Now, suppose you would like to enhance a website with some sort of automatic Twitter alerts. A blog automatically tweeting new posts is one obvious example.
The Twitter API Wiki contains all the documentation for the API. It’s best to read up on how it all works before you get started with too much API work. If you head over to the REST API page, the part we’re mainly interested is the statuses/update function. To make use of it, we need to send an HTTP POST request to http://twitter.com/statuses/update.format. The format part would be replaced with either xml or json, depending on the format we want the response to be in. Let’s go with XML.
The update function accepts two parameters in the request, status, which is the message to be posted, and the optional in_reply_to_status_id, which is used when the tweet to be posted is a reply to a user.
First, let’s prepare the necessary information and store it in variables.
$twitter_api_url = "http://twitter.com/statuses/update.xml";
$twitter_data = "status=Visit http://www.webmaster-source.com for PHP tips and tutorials!";
$twitter_user = "your_user_name";
$twitter_password = "your_password";
The $twitter_data variable contains the message to be posted to Twitter, which you must ensure is 140 characters or less before posting. You could use strlen() to do so when you ready the data to be sent, and truncate it if it’s too long. The status= before the message is the POST variable, the parameter for the API.
You’ll want to fill-in your Twitter username and password into the $twitter_user and $twitter_password variables, so the script can login and post to your account.
To send the request, we will use cURL, which is included on most servers. First we initiate cURL and pass it the URL we will be sending the request to:
$ch = curl_init($twitter_api_url);
Next we set the cURL options for the request. CURLOPT_POST to specify a POST request, CURLOPT_POSTFIELDS to set the data to be sent, CURLOPT_USERPWD to authenticate, and a few others that are necessary.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $twitter_data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "{$twitter_user}:{$twitter_password}");
Next we execute the request, capture the HTTP response code, and close our cURL session.
$twitter_data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
All that’s left really is to see whether it worked or not. Since we have our handy $httpcode variable, we can just run a conditional statement to see if the response code is equal to 200 (which means everything went okay).
if ($httpcode != 200) {
echo "<strong>Don't Panic!</strong> Something went wrong, and the tweet wasn't posted correctly.";
}
This is a fairly simplistic example. Obviously you would have to expand upon it to make it useful. You’ll need to prepare and pass data to it in some way, for one. If your messages will be accompanied by links, you’ll want to run them through a URL shortener first (Bit.ly has an API that you can use in a similar manner to Twitter’s to programmatically shorten URLs).
Sounds interesting.
I've been looking for some kind of script to produce tweets in the sidebar of my blog.=, maybe this is the answer.
Wow, that's ridiculously easy. I hadn't looked into hooking into the API myself yet, but I can already think of a few uses for that for automated websites…thanks for the heads up.
This was fantastic of you to write up. Thanks a ton.
It is easy. The only real problem is the security issue of storing peoples' Twitter usernames and passwords for things. Not something I generally like to do, for several reasons. (People don't seem to mind that much for some reason, though.) OAuth mitigates the problem, but it's a lot more complicated.
Fantastic! And it works a dream. Nice and bare-bones code which can easily be modified to do anything.
I've ported this code over to use in ColdFusion and it's worked just fine for several weeks. Suddenly, without any changes to my code, posts have stopped appearing. I'm still getting a "200 OK" as a return code. Any ideas?
I'm not sure… I don't have any ColdFusion experience. Did any of your server configurations change, possibly?
I'm on a shared hosting plan. To the best of my knowledge, nothing has changed.
Your host could have changed something, Twitter could have changed something, or there could have been something a bit flaky in your code. I'm not fluent in CF, but if you post it here I could have a quick look just to see if anything jumps out at me…
Appreciate the help so far. Here's the snippet:
<CFHTTP url="http://twitter.com/statuses/update.xml" method="POST" username="useridhere" password="passwordhere" charset="UTF-8">
<CFHTTPPARAM type="FORMFIELD" name="user" value="useridhere">
<CFHTTPPARAM type="FORMFIELD" name="password" value="passwordhere">
<CFHTTPPARAM type="FORMFIELD" name="status" value="#form.ttext#">
</CFHTTP>
<CFOUTPUT>#cfhttp.StatusCode#</CFOUTPUT>
Nothing glaringly obvious, though as I mentioned I don't really have any CF experience. Have you tried hard-coding the values to be sent (e.g. the username and password, then try the status) and running the script so you can see if the request will complete.
That way you can eliminate the possibility that it's a problem with the input not being passed properly to Twitter.
Will have to experiment a bit. Of course, today it worked. First time in nearly a month. Hiccup? No changes on my end…
Thanks so much for this.
Solved all my twitter-PHP-related problems
Is there any way to change the "via API" bit that appears next to the new status?
Cheers
Not using basic authentication. If you go the OAuth route, which is a lot more complicated to setup, the via field will update to be the name of the registered OAuth application.
Cool, I'll read into it
Thanks very much!
This can also be done from a VbScript or HTA file. Tracking your followers is also an option with the Twiiter API.
There is more about this on http://sitejunction.awardspace.....pt_tweet...
Should this work using https in the $twitter_api_url?
I *think* so. Give it a try.
Wow thats really very nice i use to mange many website and i need to login to twitter to post the updates not i can do it easily.
Thanks very much! I can’t describe how grateful I am for this tutorial. This was exactly what I needed and worked at first try.
Thanks!!
Many thanks!! Simple but effective twitter update PHP script.
Great work! Thank you!
Nice article with a very good explanation of the implementation steps. If you’re interested in another angle on publishing from php to twitter, you can find script, that includes bit.ly url shortening, and content shortening here: http://tips4php.net/2010/03/au.....n-twitter/
Pretty awesome post. I think I’m going to have a simple text file of tweets that I write ahead of time, and have a cron job run this script (modified) from my godaddy hosting account at various times of the day. Thanks for the info!
how i can make my own update.xml?? can you give me the script update.xml?
THANK YOU! That just saved me a huge amount of time!!
Excellent, thank you.
Unfortunately, this will break on 16-Aug-10 when Twitter stop Basic Auth from working, and force everyone to use OAuth. What’s the easiest way of doing this kind of thing with OAuth?
It’s a little bit more complicated. You could take a look at the wiki: http://apiwiki.twitter.com/OAuth-Examples
Is there such a thing for Facebook as well?
This is great! Thank you man!
Weird.