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 http://twitter.com and register an application from the http://dev.twitter.com/apps 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);

Posting

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);

Displaying

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:

<ul>
<?php foreach ($statuses as $status): ?>
	<li><a href="http://twitter.com/<?= $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>
	</li>
<?php endforeach ?>
</ul>

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.

Searching

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));

16 years ago in section PHP | blog written by David Grudl | back to top

You might be interested in

Comments

  1. veena #1

    avatar

    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

    16 years ago | reagoval [2] Inza
  2. Inza #2

    avatar

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

    16 years ago
  3. Marcus Povey #3

    avatar

    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:’));

    16 years ago | reagoval [4] David Grudl
  4. David Grudl #4

    avatar

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

    16 years ago
  5. Martin Ragg #5

    avatar

    I've s.th. “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,
    martin

    16 years ago | reagoval [6] David Grudl
  6. David Grudl #6

    avatar

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

    16 years ago
  7. Martin Ragg #7

    avatar

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

    16 years ago
  8. Ryan Taylor #8

    avatar

    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!

    16 years ago | reagoval [10] David Grudl
  9. Robb Corrigan #9

    avatar

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

    I've given you a plug here: http://twitcharts.com/about.php

    Thanks again!

    16 years ago
  10. David Grudl #10

    avatar

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

    16 years ago
  11. Nathan #11

    avatar

    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: https://www.alephnaught.com/…one-problem/ but my php knowledge is too limited to implement it with your solution.

    Thanks,
    Nathan

    16 years ago
  12. Dragon Jake #12

    avatar

    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 ;]

    14 years ago
  13. srigi #13

    avatar

    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?
    THX.

    14 years ago | reagoval [14] David Grudl
  14. David Grudl #14

    avatar

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

    14 years ago
  15. Fost #15

    avatar

    Hi David,

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

    Thanks!

    14 years ago
  16. Onecar #16

    avatar

    Hello,
    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.

    14 years ago | reagoval [17] David Grudl
  17. David Grudl #17

    avatar

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

    14 years ago
  18. martin131 #18

    avatar

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

    14 years ago
  19. David Grudl #19

    avatar

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

    14 years ago | reagoval [20] martin131
  20. martin131 #20

    avatar

    #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.

    14 years ago
  21. David Grudl #21

    avatar

    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(...));
    11 years ago
  22. Keith #22

    avatar

    How would I favorite a tweet?

    11 years ago
  23. Keith #23

    avatar

    NM, figured it out:

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

    11 years ago
  24. GCube #24

    avatar

    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

    11 years ago | reagoval [26] David Grudl
  25. drknickel #25

    avatar

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

    Thats it :)

    11 years ago | reagoval [26] David Grudl
  26. David Grudl #26

    avatar

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

    11 years ago
  27. fans #27

    avatar

    Hello David,

    How can I post a pic using this class?

    Thanks in advance.

    11 years ago | reagoval [28] David Grudl
  28. David Grudl #28

    avatar

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

    11 years ago
  29. fans #29

    avatar

    Thanks a lot. Regards.

    11 years ago
  30. Phil #30

    avatar

    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 “https://davidgrudl.com/images/david-grudl.jpg”

    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!’, ‘https://davidgrudl.com/images/david-grudl.jpg’);

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

    Thanks,
    Phil

    11 years ago | reagoval [31] David Grudl
  31. David Grudl #31

    avatar

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

    11 years ago
  32. Phil #32

    avatar

    Thanks David, that was it.

    11 years ago
  33. Saed #33

    avatar

    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 https://web.archive.org/…y.comxa.com/

    Any idea how to resolve it ,thanks in advance

    11 years ago
  34. jahrvos #34

    avatar

    Hi, thanks a lot for the code

    I get a server error 401
    What can I do?

    10 years ago
  35. alex #35

    avatar

    David, I actually created a new function like so:

    public function sendGeo($message, $lat, $lng, $media = null)
    	{
    		return $this->request(
    	 'statuses/update',
    			'POST',
    			array('status' => $message,
    			'lat' => $lat,
    			'long' => $lng,
    			'display_coordinates' => true)
    		);
    	}
    10 years ago
  36. CreativeWolf #36

    avatar

    Hi David,

    Great work!

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

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

    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.

    Thanks

    CreativeWolf

    10 years ago | reagoval [37] David Grudl
  37. David Grudl #37

    avatar

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

    10 years ago
  38. Dave #38

    avatar

    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: https://twitter.com/…068253995008

    Any hints for getting line breaks into a Tweet?

    Many thanks in advance!

    10 years ago | reagoval [39] David Grudl
  39. David Grudl #39

    avatar

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

    10 years ago | reagoval [40] Dave
  40. Dave #40

    avatar

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

    10 years ago
  41. Steve #41

    avatar

    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

    10 years ago | reagoval [42] David Grudl
  42. David Grudl #42

    avatar

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

    10 years ago
  43. Barry B #43

    avatar

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

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

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

    10 years ago
  44. fabio #44

    avatar

    Hi,
    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,
    Fabio

    9 years ago
  45. Max #45

    avatar

    Hi,

    How can I get a mute function?

    7 years ago
  46. Max #46

    avatar

    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);
    	}
    7 years ago
  47. thamman_neha #47

    avatar

    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.

    6 years ago

This article has been closed. It is no longer possible to add comments.


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í.