Na navigaci | Klávesové zkratky

Twitter for PHP

Twitter for PHP is a very small and easy-to-use library for sending messages to Twitter and receiving status updates with OAuth support.

Download Twitter for PHP 3.5

It requires PHP (version 5 or newer) with CURL extension and is licensed under the New BSD License. You can obtain the latest version from our GitHub repository or install it via Composer:

php composer.phar require dg/twitter-php

Twitter requires SSL/TLS as of January 14th, 2014. Update to the last version.

Getting started

Sign in to the and register an application from the page. Remember to never reveal your consumer secrets. Click on My Access Token link from the sidebar and retrieve your own access token. Now you have consumer key, consumer secret, access token and access token secret.

Create object using application and request/access keys:

$twitter = new Twitter($consumerKey, $consumerSecret,
	$accessToken, $accessTokenSecret);


The send() method posts your status. The message must be encoded in UTF-8:

$twitter->send('I am fine today.');

You can append picture:

$twitter->send('This is my photo', $imageFile);


The load() method returns the 20 most recent status updates posted in the last 24 hours by you:

$statuses = $twitter->load(Twitter::ME);

or posted by you and your friends:

$statuses = $twitter->load(Twitter::ME_AND_FRIENDS);

or most recent mentions for you:

$statuses = $twitter->load(Twitter::REPLIES);

Extracting the information from the channel is easy:

<?php foreach ($statuses as $status): ?>
	<li><a href="<?= $status->user->screen_name ?>">
		<?= htmlspecialchars($status->user->name) ?></a>:

		<?= Twitter::clickable($status) ?>

		<small>at <?= date("j.n.Y H:m", strtotime($status->created_at)) ?></small>
<?php endforeach ?>

The static method Twitter::clickable() makes links in status clickable. In addition to regular links, it links @username to the user’s Twitter profile page and links hashtags to a Twitter search on that hashtag.


The search() method provides searching in twitter statuses:

$results = $twitter->search('#nette');

The returned result is a again array of statuses.

Error handling

All methods throw a TwitterException on error:

try {
	$statuses = $twitter->load(Twitter::ME);
} catch (TwitterException $e) {
	echo "Error: ", $e->getMessage();

Additional features

The authenticate() method tests if user credentials are valid:

if (!$twitter->authenticate()) {
	die('Invalid name or password');

Other commands

You can use all commands defined by Twitter API 1.1. For example GET statuses/retweets_of_me returns the array of most recent tweets authored by the authenticating user:

$statuses = $twitter->request('statuses/retweets_of_me', 'GET', array('count' => 20));


  1. veena #1


    Díky Davide, zrovna Twitter chceme použít v jednom novém “omračujícím ?” projektu. Tak jsi nám to jenom ulehčil!

    Díky, pokud se projekt povede, pozvu tě na pivo ;-D

    před 16 lety | reagoval [2] Inza
  2. Inza #2


    #1 veena, Tak to nás bude víc, co dělají na “omračujících” projektech a pozvou tě na pivo:-)

    před 16 lety
  3. Marcus Povey #3


    Twitter broke/fixed their API recently and now this library returns 417 when attempting to post.

    Fix: Add the following line to twitter.class.php:113 just after the other curl_setopt lines and be fore the if ($post)…

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(‘Expect:’));

    před 15 lety | reagoval [4] David Grudl
  4. David Grudl #4


    #3 Marcus Povey, thank you Marcus, I have updated it.

    před 15 lety
  5. Martin Ragg #5


    I've “strange” – I'm using your class and normally all is working fine – today I twittered “Königinnen der Nacht” and it seems to me that the class “killed” some letters. On twitter always there was only “Köinnen der Nacht” – do you have an idea?
    (Directly from twitter all was working fine .. )
    best regards,

    před 15 lety | reagoval [6] David Grudl
  6. David Grudl #6


    #5 Martin Ragg, And was the message encoded in UTF-8?

    před 15 lety
  7. Martin Ragg #7


    #10 David Grudl – Oh sorry, my fault – there was no utf8_encode, I fixed my script and it seems to be working finde

    před 15 lety
  8. Ryan Taylor #8


    Hello David. Thank you very much for writing this PHP class for Twitter. I have one question: is there anyway to return the status ID of a tweet using the send() method? Currently it looks as though you have it returning only a boolean true/false.

    Thanks again!

    před 15 lety | reagoval [10] David Grudl
  9. Robb Corrigan #9


    Hello David, excellent API! I'm using this in a simple hobby project that I've built which allows people to tweet Google charts.

    I've given you a plug here:

    Thanks again!

    před 15 lety
  10. David Grudl #10


    #8 Ryan Taylor, Ryan I have updated send() method, it returns ID on success and false on failure now.

    před 15 lety
  11. Nathan #11


    It seems that Twitter returns tweets in UTC time. Is there an easy way to make the time and date conform to my time zone?
    I saw something that might help, here:…one-problem/ but my php knowledge is too limited to implement it with your solution.


    před 15 lety
  12. Dragon Jake #12


    Díky Davide za aktualizaci! Už jsem měl plány, že podporu ve svém forku nějak zkompletním (třeba odstraním zbytečnou druhou knihovnu a zlepším celý proces autorizace, jak jsi udělal Ty) a nenechám ji v tomhle stavu “nějak to funguje na to, co potřebuju”. Jsem rád, že je mohu zapomenout a věnovat se jiným věcem ;]

    před 14 lety
  13. srigi #13


    Hello David, thank for good job. But I got problem, maybe I'm just blind or stupid, but how do I get $accessToken and $accessTokenSecret. I think that sctript must run OAuth loop (my app, twitter, return to my app), but this isn't covered in this article. Can you please add short desctiption/tutorial on this?

    před 14 lety | reagoval [14] David Grudl
  14. David Grudl #14


    #13 srigi, RTFM 🙂 There is a readme.txt file with complete explanation.

    před 14 lety
  15. Fost #15


    Hi David,

    Very nice! Just one question: Is there a way of changing the limit from 24 hours for load()?


    před 13 lety
  16. Onecar #16


    is there any way how to make links in $status->text active, so I can click right away? So far I only have almost plain text, only author is a link.
    Thanks for your response.

    před 13 lety | reagoval [17] David Grudl
  17. David Grudl #17


    #16 Onecar, in last revision there is a method Twitter::clickable().

    před 13 lety
  18. martin131 #18


    Ahoj, vrací se v poli i přímý odkaz na tweet? Plánuješ případně tuto možnost přidat??

    před 13 lety
  19. David Grudl #19


    Ten se dá poskládat, viz příklady v článku.

    před 13 lety | reagoval [20] martin131
  20. martin131 #20


    #19 David Grudl, Jsem asi slepý, ani po druhém dlouhém zkoumání jsem to v těch příkladech nenašel. :D Nakonec jsem se podíval do wiki Twitter API.

    před 13 lety
  21. David Grudl #21


    How to get a list of followers?

    function getAllFollowers($userName, $twitter)
    	$followers = array();
    	$cursor = '-1';
    	do {
    		$channel = $twitter->request('followers/ids', 'GET', array('cursor' => $cursor, 'screen_name' => $userName));
    		$followers = array_merge($followers, $channel->ids);
    		if (empty($channel->next_cursor_str)) {
    			return $followers;
    		$cursor = $channel->next_cursor_str;
    	} while (true);
    // usage
    $followers = getAllFollowers('davidgrudl', new Twitter(...));
    před 10 lety
  22. Keith #22


    How would I favorite a tweet?

    před 10 lety
  23. Keith #23


    NM, figured it out:

    $status = $twitter->request(‘favorites/create’, ‘POST’, array(‘id’ ⇒ $status->id_str));

    před 10 lety
  24. GCube #24


    Hi David,
    I knew that Twitter changed its auth method again using SSL this time, how we can update the class using SSL OAuth?
    Thanks in advance

    před 10 lety | reagoval [26] David Grudl
  25. drknickel #25


    Easy solution:
    Just open twitter.class and change line 18 to
    const API_URL = ‘#stary-odkaz-#stary-odkaz-’;

    Thats it :)

    před 10 lety | reagoval [26] David Grudl
  26. David Grudl #26


    #24 GCube, #25 drknickel I have released fixed version with SSL support

    před 10 lety
  27. fans #27


    Hello David,

    How can I post a pic using this class?

    Thanks in advance.

    před 10 lety | reagoval [28] David Grudl
  28. David Grudl #28


    #27 fans, Update to the last version, there is support for uploading pictures via Twitter::send($status, $imageFile).

    před 10 lety
  29. fans #29


    Thanks a lot. Regards.

    před 10 lety
  30. Phil #30


    Thanks so much David, what a great script. When I try to upload an image using
    Twitter::send($status, $image)
    I get this error:
    Error: Server error: couldn't open file “”

    I've tried lots of different images and all give the same error. Should I provide the image in this format?
    $tweet = $twitter->send(‘Happy Wednesday!’, ‘’);

    If I post text only without an image it works fine.


    před 10 lety | reagoval [31] David Grudl
  31. David Grudl #31


    #30 Phil, maybe it works only with local images, stored on file system.

    před 10 lety
  32. Phil #32


    Thanks David, that was it.

    před 10 lety
  33. Saed #33


    Hi ,
    Great work but I get this error

    Fatal error: Uncaught exception ‘TwitterException’ with message ‘Server error: couldn't connect to host’ in /home/a8771684/public_html/twitter.class.php:256 Stack trace: #0 /home/a8771684/public_html/twitter.class.php(201): Twitter->request(‘search/tweets’, ‘GET’, Array) #1 /home/a8771684/public_html/default.php(17): Twitter->search(‘#Egypt’) #2 {main} thrown in /home/a8771684/public_html/twitter.class.php on line 256

    From this webpage…

    Any idea how to resolve it ,thanks in advance

    před 10 lety
  34. jahrvos #34


    Hi, thanks a lot for the code

    I get a server error 401
    What can I do?

    před 10 lety
  35. alex #35


    David, I actually created a new function like so:

    public function sendGeo($message, $lat, $lng, $media = null)
    		return $this->request(
    			array('status' => $message,
    			'lat' => $lat,
    			'long' => $lng,
    			'display_coordinates' => true)
    před 10 lety
  36. CreativeWolf #36


    Hi David,

    Great work!

    While using your example for fetching followers, I tried the following:

    <?php foreach ($followers as $follower ): ?>
    	<?php echo $follower; ?>
    <td><?php echo $follower->screen_name; ?> </td>
    	<?php endforeach ?>

    I'm getting an error message “Notice: Trying to get property of non-object in followers.php”

    Please point me how to fetch the Screen Name and User Name.



    před 10 lety | reagoval [37] David Grudl
  37. David Grudl #37


    #36 CreativeWolf, function loadUserFollowers() returns only ids of followers, see…ollowers/ids. To fetch screen name use function loadUserInfoById().

    před 9 lety
  38. Dave #38


    Thank you, David, for this useful library!
    I tried to get line breaks into a tweet. So in send.php I wrote:

    $tweet = $twitter->send( 'First Line \n Second Line \n Third Line' );

    This was the result:…068253995008

    Any hints for getting line breaks into a Tweet?

    Many thanks in advance!

    před 9 lety | reagoval [39] David Grudl
  39. David Grudl #39


    #38 Dave, use double quotes ie. "First\nSecond line".

    před 9 lety | reagoval [40] Dave
  40. Dave #40


    #39 David Grudl, Great! Works perfectly. Thank you very much!

    před 9 lety
  41. Steve #41


    Hi David,
    Great work! All was going well until I did this…
    $tweet = $twitter->send(‘@username’,$imagefile);
    fails with
    Error: Server error: couldn't open file “username”

    Is it not possible to send a reply with an image please?
     – Steve

    před 9 lety | reagoval [42] David Grudl
  42. David Grudl #42


    #41 Steve, fixed in 3.5, but it requires PHP >= 5.5.0

    před 9 lety
  43. Barry B #43


    Can't tweet an image! Here is my code:

    $twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
    try {
    $tweet = $twitter->send(“Visit our site at”,$image);
    catch (TwitterException $e) {
    echo 'Error: ' . $e->getMessage();

    The above code sends the text ‘Visit our site at’ but doesn't attach the image with it. What am I missing?

    před 9 lety
  44. fabio #44


    I use you library with success, is very simple to use it, thanks!
    I want to add a http address to the tweet, how I can do it if my text and link exceed the 140 characters?
    Thank's in advance,

    před 8 lety
  45. Max #45



    How can I get a mute function?

    před 7 lety
  46. Max #46


    Try to make a mute-function but the page gives an error.

    Here my code:

    		return $this->request('mutes/users/create', [
    			'user_id' => $username,
    			'follow' => $count);
    před 7 lety
  47. dawood #47


    hi david
    help me with uploading video

    před 6 lety
  48. thamman_neha #48


    Hi David,
    I'm trying to upload image via upload method using local storage, only text is being posted on twitter, but not image, nor it gives any error regarding to image upload.

    před 5 lety

Tento článek byl uzavřen. Už není možné k němu přidávat komentáře.

phpFashion © 2004, 2024 David Grudl | o blogu

Ukázky zdrojových kódů smíte používat s uvedením autora a URL tohoto webu bez dalších omezení.