Post to Twitter from PHP script

Twitter is a great platform for publishing news, and interacting with your users. However publishing content on multiple platforms can be very time consuming unless you have some tools for optimizing the workflows.

In this post you’ll learn how to create a php script that can automatically publish  your website content on Twitter, and automatically optimizes content within the 140 character limit per Twitter post.

Important update! – Twitter don’t support http authentication anymore, which makes this script obsolete. See the new OAuth Post to Twitter script here

One of the important things about posting content  on Twitter, is the fact that messages can’t be longer that 140 characters. If messages exceeds this limit, they won’t be posted. This means that the length of posts, and optimization of  post content within the 140 character limit is very important.  Our solution for publishing content on Twitter contains the following elements for optimizing the content: a integrated url shortener and a content shortener. url shortening

If your content contains url’s, there is a high risk that the url will consume a high percentage of the 140 character allowed in the post, which isn’t optimal. Therefore  a url shortening service like is very useful for reducing the length of url’s.

In this script we’ll use the api which is free to use, and allows us to fully automate the url shortening. Before you can use the API, you need to sign up for a API key and login from the site. The url shortening code is based on code from James Cridland.

function get_short_link($url) {
  $bitly_login="< login>";
  $bitly_apikey="< api key";
  $api_call = file_get_contents("".$url."&login=".$bitly_login."&apiKey=".$bitly_apikey);

  if ($bitlyinfo['errorCode']==0) {
    return $bitlyinfo['results'][urldecode($url)]['shortUrl'];
  } else {
    return false;

Usage of the function is simple, call the function with a url eg: “” and then function will return a shortened version of the link: ““.

Content length optimization

Even if the url has been shortened, it’s still important that we secure that the total length of the tweet stays below 140 characters. To ensure, this we’re creating a small function that counts the characters in the shortened url, and in the message, and shortens the message if necessary.

// reduce joke text to twitter format
$length = strlen($text);
$ch = 70; //if the text is above 70 characters, the message is shortened
if ($length >= $ch) {
  $foo1 = (substr("$text", 0, $ch));
  $foo = "$foo1...";
} else {
  $foo = $text;

Sending to Twitter

Now that the content has been optimized it’s time to build the component that can send the tweet to Twitter. For this purpose a function using CURL is very useful


// A simple function using Curl to post (GET) to Twitter
// Kosso : March 14 2007

function postToTwitter($username,$password,$message){

 $host = "".urlencode(stripslashes(urldecode($message)));

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $host);
 curl_setopt($ch, CURLOPT_VERBOSE, 1);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
 curl_setopt($ch, CURLOPT_POST, 1);

 $result = curl_exec($ch);
 // Look at the returned header
 $resultArray = curl_getinfo($ch);


 if($resultArray['http_code'] == "200"){
 $twitter_status='Your message has been sended! <a href="'.$username.'">See your profile</a>';
 } else {
 $twitter_status="Error posting to Twitter. Retry";
 return $twitter_status;

You should save this function in a separate file named “twitter_class.php”

After you have created the twitter_class.php file on you server, the next code snippet passes content to “twitter_class.php” so the content gets posted on Twitter:

$twitter_username='you twitter username';
$twitter_psw='your twitter password';
$twitter_message= ''.$foo.'. See more here: '.$shortlink.'';
} else {
  $twitter_status=postToTwitter($twitter_username, $twitter_psw, $twitter_message);
echo ("$twitter_status");

The output of the script looks like this:

Great flash game: Kingdom of the Wind. As a Wind Warrior Leader, you should able to lead your army…. See more here:

So that’s it. The total script looks like this:

// short link function
include '<insert url to the Twitter php class on your server here>';
function get_short_link($url) {
  $bitly_login="< login>";
  $bitly_apikey="< api key";
  $api_call =  file_get_contents("".$url."&login=".$bitly_login."&apiKey=".$bitly_apikey);

  if ($bitlyinfo['errorCode']==0) {
    return $bitlyinfo['results'][urldecode($url)]['shortUrl'];
  } else {
    return false;

// reduce text to twitter format
$length = strlen($text);
$ch = 70; //if the text is above 70 characters, the message is shortened
if ($length >= $ch) {
  $foo1 = (substr("$text", 0, $ch));
  $foo = "$foo1...";
} else {
  $foo = $text;

// send tweet to Twitter
$twitter_username='you twitter username';
$twitter_psw=your twitter password";
$twitter_message= ''.$foo.'. See more here: '.$shortlink.'';
} else {
  $twitter_status=postToTwitter($twitter_username, $twitter_psw,  $twitter_message);
echo ("$twitter_status");

Next steps

If you have some kind of CMS system, you can integrate the script in your publishing process, so every time new content is published on your website, an tweet is automatically posted on Twitter.

You can also create a cron job that automatically pushes different kinds of content from your site to Twitter – the possibilities are endless :-)

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

44 Replies to Post to Twitter from PHP script

  1. Jørgen says:

    Great article – just what I was looking for. This saves me a lot of research in Google

  2. Dobiatowski! says:

    I made few changes but all idea and sources was very good, regards

  3. jhnidk says:

    Do you get any error messages?

  4. hey, above information is very helpful and so easy to implement. I was so worried before looking at this article, but things are done much easily and quickly than expected :)

    thanks a lot !

    Keep up some good postings.


    Team | Joomla Outsource India

  5. Ashley says:

    Excellent idea. So, if I have a script that uploads an image into a database, how can I call on this class to run and send the tweet?

    Thanks for your time,

  6. jhnidk says:


    I would wrap the code inside a function – eg:


    And then call the send_tweet(); function each time you upload a new image.
    Br. Jørgen

  7. Ashley says:

    Also, when trying to run, I got an error because the postToTwitter function could not be found. Is this not in the twitter class attached to this post?

  8. Nice post. I like your blog.

  9. Great site. A lot of useful information here. I’m sending it to some friends!

  10. My cousin recommended this blog and she was totally right keep up the fantastic work!

  11. brian says:

    what am i missing here i get two errors

    Notice: Undefined variable: shortlink
    Call to undefined function postToTwitter()

  12. brian says:

    fixed first error forgot to call the function i guess that would help but still getting this

    Call to undefined function postToTwitter()

  13. jhnidk says:

    Maybe you haven’t downloaded and included the twitter php class?, I have updated the script to make this more visible

  14. The Twitter PHP Class has been updated (I guess…).

    You can use it like that :

    $twitter = new Twitter($twitter_username, $twitter_password);
    $twitter_status = $twitter->send($twitter_message);

  15. suresh says:

    I am getting this error

    Warning: require(twitter_api.php) [function.require]: failed to open stream: No such file or directory

    What could be the reason ,help me

  16. jhnidk says:

    Have you downloaded and included the required twitter API class? – the error message indicates that you’re missing this file, or poinsto the wrong location of the file.

  17. Scott Taurad says:

    fantastic idea. We have something very similar using wordpress to publish

  18. mr bob says:

    where do you download twitter api, I see the class but no api?


  19. jhnidk says:

    The Twitter API is a online service. You can see more about the Twitter API here:

  20. boss says:


    I would like to know if the script can be modify to just tweet random msg every time the cron job is set to.

    For example this is the old auto tweet using CURL, maybe you can get some idea

  21. jhnidk says:

    Sure – If you’re storing your content in a database, you just need to add a few lines of SQL that extracts random content, and places the text in the $text variable.

  22. boss says:

    thank you. i will try using your script and edit a few things to see if i can do it although i have a little knowledge on php.

    to make it simple, will remove the get_short_link function and the auto truncate, because the tweet msg is already in a array (which i pre set it)

  23. Yuri says:


    Great work over there! Keep going. But i have 1 problem. Where can i find the twitter API Class? You dont tell anything about it in the article… Do i have to register an application first on the twitter developers site?



  24. jhnidk says:

    Just follow the external links in the post to the Twitter Class

  25. Yuri says:

    include ‘<insert url to the Twitter php class on your server h…'

    This is the class i can download from the link. But in the last php code you do this:


    and thats the class i cant find. Or is it on ? I dont understand the russian or something like that…

  26. Hossein says:

    As much as this tutorial is so easy to understand and explains everything it has not mentioned anything about the twitter_api.php and how we can actually find this file? (Considering this is the first time a user wants to integrate twitter to a website).

    The issue is that it seems twitter will only provide an api once you explain what your application is and gets really complicated over nothing, is this really an application? Cant someone just share the file?

  27. jhnidk says:

    Hi. The Twitter API referenced in the post is actually not a API from Twitter, but a a PHP class that allows you to post content to twitter from a PHP script, so you don’t need anything form twitter besides a normal twitter account to make this script working.

  28. Steven says:

    I hate to ask this question considering others have already asked, but WHERE CAN WE DOWNLOAD the “twitter_api.php” file? You are referencing to a file that is not available for download on this page.

  29. jhnidk says:

    Hi. It’s the twitter_class that should be used. It’s updated in the source code

  30. jhnidk says:

    Thank you for the feedback – a new version of the script has been posted, now with the missing piece included :-)

  31. Jazz says:

    I am getting 401 error , I double checked the username, password and I can still login to twitter account with same credentials.

  32. jhnidk says:

    Hi, the error code is caused by Twitter not allowing http authentication anymore. You can find a the updated Twitter OAuth Post to Twitter script here

  33. Pummy Manku says:

    Thank you for the cool script. I need that to add my site rss to twitter :)

    good job.

  34. sammy says:

    sweet. thank you.

  35. SPMatthee says:

    It doesn’t work at all, since Twitter changed their API. It now is only possible through OAuth. I’ve made a post on the OAuth way of posting tweets. The post is in dutch, but the script is in english. So you can get it working easily without translating the page.

    The post is here:

  36. Pummy Manku says:


    This is a cool code/script but I added my site rss feed to feedburner and now all my links are automatically added in twitter via feedburner. This is the easiest method I have found so far.. no code or script needed. All my rss links are not auto publish in twitter :)

    Thank You
    Pummy Manku

  37. AJi Prabowo says:

    excellent advise. took time to understand the whole process. but it’s worth.


  38. Dmitri says:

    Your functions are not utf-8 safe. substr does not work correctly on unicode, so it will fail with any non-latin language. You must use mb_substr instead. The rest look OK except that utf8_encode will also fail misarably if the original encoding on the link is not in ISO-8859-1 encoding. For example, if the original url contains any unicode chars (unicode chars now allowed in urls and in domain names), then utf8_encode will completely mess up your string. You need to use other means to convert link to utf-8, like iconv()

    You should really update your article because anyone taking your code and using it with unicode strings will suffer greately.

  39. Anjaly says:

    Got an error like this.
    Basic authentication is not supported.
    What to do next?

    Thanks in advance.

  40. rusdin says:

    great, i like this script!!!

  41. comparer says:

    Great article. Thank you.

  42. elec J. says:

    I was finding similar code, your code exactly fit to my requirement. Thanks.

  43. umair says:


    I have tried this code. but its not working for me. I copy pasted the exact code. passed the username and password to the function. but it says “Error posting to Twitter. Retry”
    What possibly am i missing?

    Additional info: I am running this script on local pc. i havent tried this by uploading the file on the hosting server.


Trackbacks for this post

  1. Tweets that mention Post to Twitter from PHP script :: Tips4PHP --

Comments are now closed for this article.