Twitter for PHP is a very small and easy-to-use library for sending messages to Twitter and receiving status updates with OAuth support.
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));
Comments
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
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:-)
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:’));
David Grudl #4
#3 Marcus Povey, thank you Marcus, I have updated it.
Martin Ragg #5
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
David Grudl #6
#5 Martin Ragg, And was the message encoded in UTF-8?
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
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!
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. http://twitcharts.com/
I've given you a plug here: http://twitcharts.com/about.php
Thanks again!
David Grudl #10
#8 Ryan Taylor, Ryan I have updated send() method, it returns ID on success and false on failure now.
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: https://www.alephnaught.com/…one-problem/ but my php knowledge is too limited to implement it with your solution.
Thanks,
Nathan
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 ;]
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?THX.
David Grudl #14
#13 srigi, RTFM 🙂 There is a readme.txt file with complete explanation.
Fost #15
Hi David,
Very nice! Just one question: Is there a way of changing the limit from 24 hours for load()?
Thanks!
Onecar #16
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.
David Grudl #17
#16 Onecar, in last revision there is a method Twitter::clickable().
martin131 #18
Ahoj, vrací se v poli i přímý odkaz na tweet? Plánuješ případně tuto možnost přidat??
David Grudl #19
Ten se dá poskládat, viz příklady v článku.
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.
David Grudl #21
How to get a list of followers?
Keith #22
How would I favorite a tweet?
Keith #23
NM, figured it out:
$status = $twitter->request(‘favorites/create’, ‘POST’, array(‘id’ ⇒ $status->id_str));
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
drknickel #25
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 :)
David Grudl #26
#24 GCube, #25 drknickel I have released fixed version with SSL support
fans #27
Hello David,
How can I post a pic using this class?
Thanks in advance.
David Grudl #28
#27 fans, Update to the last version, there is support for uploading pictures via
Twitter::send($status, $imageFile)
.fans #29
Thanks a lot. Regards.
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 “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
David Grudl #31
#30 Phil, maybe it works only with local images, stored on file system.
Phil #32
Thanks David, that was it.
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 https://web.archive.org/…y.comxa.com/
Any idea how to resolve it ,thanks in advance
jahrvos #34
Hi, thanks a lot for the code
I get a server error 401
What can I do?
alex #35
David, I actually created a new function like so:
CreativeWolf #36
Hi David,
Great work!
While using your example for fetching followers, I tried the following:
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
David Grudl #37
#36 CreativeWolf, function
loadUserFollowers()
returns only ids of followers, see https://dev.twitter.com/…ollowers/ids. To fetch screen name use functionloadUserInfoById()
.Dave #38
Thank you, David, for this useful library!
I tried to get line breaks into a tweet. So in send.php I wrote:
This was the result: https://twitter.com/…068253995008
Any hints for getting line breaks into a Tweet?
Many thanks in advance!
David Grudl #39
#38 Dave, use double quotes ie.
"First\nSecond line"
.Dave #40
#39 David Grudl, Great! Works perfectly. Thank you very much!
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
David Grudl #42
#41 Steve, fixed in 3.5, but it requires PHP >= 5.5.0
Barry B #43
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?
fabio #44
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
Max #45
Hi,
How can I get a mute function?
Max #46
Try to make a mute-function but the page gives an error.
Here my code:
thamman_neha #47
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.
This article has been closed. It is no longer possible to add comments.