I am trying to create a randomly generated phrase that can easily be shared amongst social media websites, specifically twitter. I am using the following PHP code to generate a random phrase.
This code looks in 'responses.txt' for a line with a phrase and I can call that line.
<!-- HEADER -->
<?php
$randomThings = file('**responses.txt**', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>
<!-- CALL SCRIPT -->
<?php
echo $randomThings[mt_rand(0,count($randomThings)-1)];
?>
How would I be able to have, for example, retweet button next to this generated line that retweets the phrase with a predetermined #hatchtag (via #[websitename]).
I'm more interested in the twitter aspect, but other social media websites could help other people.
The re-tweet intent itself has problems right now. It's been filed as a bug since November so I don't think you'll want to use the re-tweet functionality from an external website. You can simulate a re-tweet with a regular tweet intent and pre-filling in the text, (which sounds like what you actually want to do). With the tweet intent you send a HTTP request to https://twitter.com/intent/tweet. You could then include the text parameter to pre-fill the text when the HTTP request is sent, or the link is clicked.
Using your example it would look something like this:
<!-- HEADER -->
<?php
$randomThings = file('**responses.txt**', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>
<!-- CALL SCRIPT -->
<?php
$newThings = $randomThings[mt_rand(0,count($randomThings)-1)]; //must evaluate to a string
echo $newThings;
echo 'Link text';
?>
this would be an unstyled link instead of a "button" but you can adapt it to be a button using standard HTML/CSS styling.
ref: https://dev.twitter.com/docs/intents
Related
I'm updating my site to a more mobile friendly responsive design using jquerymobile. Usually I have the user login and after checking the details are correct it will refresh them onto a new page.
However, I can't get this working with jquerymobile. Presumably this is because of the Ajax override features? Ajax is currently foreign to me :)
The abridged script is like below:
else
//else, all ok proceed with login
{
if(isset($_GET['redirect']))
{header ("Refresh: 0; URL=" . $_GET['redirect'] . "");}
else{header ("Refresh: 0; URL=cohome.php");
echo "Your login was successful, you are being redirected in one second <br />";
echo "(If your browser doesn't support this, click here)";}
}
many thanks
Actually, to simplify things. I have the same problem with my logout button.
<a href="logout.php">
which leads to
<?php
session_start();
// make double sure that logged out.
$_SESSION['logged'] = "0";
session_destroy();
header("Refresh: 0; URL=index.php");
echo "You have been logged out.<br />";
echo "You are being redirected to the homepage!<br />";
echo "(If your browser doesn't support this, click here)";
?>
Unfortunately, no redirect occurs. It works fine on my standard site, only since starting to change over to jquery mobile.
Ah ok. It seems to work fine if I turn off ajax, using "data-ajax=false".
<form name="login" id="login" action="<?php echo "processCoLogin.php?".$_SERVER['QUERY_STRING']; ?>" data-ajax=false method="post">
or
<a href="logout.php" class="ui-btn" data-ajax=false>Log out</a>
But I'd prefer a solution where I didn't have to turn off ajax & could redirect using header(location) still.
A header with a refresh of 0 makes not much sense. Consider using
header('location:' . $_GET['redirect']);
instead. Or, if you wish to display the redirect message, increase the refresh time. Last, but not least, you could also echo a refresh:
echo "<meta http-equiv='refresh' content='3; url=" . $_GET['redirect']) . "'>";
However, using meta-refresh is not recommended. But if you are using JS and rely on it, you could also use a JS redirection:
echo "setTimeout(\"location.href = '" . $_GET['redirect']) . "';\", 3000);";
There are several ways, but a PHP refresh with 0 seconds isn't the best idea in my opinion.
Is there any way of building a profile image url with user id or screen name? I store user ids in database but i don't want to store profile image url.
edit:
I don't want to make a api call too. I want to put user_id inside a url like
<img src="https://twitter.com/users/profile_pic?user_id=123"> Is there a url to do this?
With API 1.1 you can achieve this using these URLs:
https://twitter.com/[screen_name]/profile_image?size=mini
https://twitter.com/[screen_name]/profile_image?size=normal
https://twitter.com/[screen_name]/profile_image?size=bigger
https://twitter.com/[screen_name]/profile_image?size=original
Official twitter documentation Profile Images and Banners
Example
https://twitter.com/TwitterEng/profile_image?size=original
will redirect to
https://pbs.twimg.com/profile_images/875168599299637248/84CkAq6s.jpg
As of June 2020, both the accepted answer and avatars.io no longer work. Here are two alternatives:
unavatar.io
(formerly unavatar.now.sh)
Unavatar can get pictures from quite a few different places including Twitter. Replace [screen_name] in the URL below with the Twitter username you want.
<img src="https://unavatar.io/twitter/[screen_name]" />
For example:
<img src="https://unavatar.io/twitter/jack" width="100" height"100" />
If the demo above ever stops working, it's probably because unavatar.io is no longer available.
Unavatar is open source though, so if it does go down, you can deploy it yourself from the GitHub repo — it even has "Deploy to Vercel/Heroku" buttons. The code to fetch Twitter avatars specifically is here, so you could also use that as part of your own backend.
twivatar.glitch.me
⚠️ As of July 2021 this option no longer works, see the one above instead!
If you want an alternative, you can also use twivatar.glitch.me. Replace [screen_name] in the URL below with the Twitter username you want.
<img src="https://twivatar.glitch.me/[screen_name]" />
For example:
<img src="https://twivatar.glitch.me/jack" width="100" height"100" />
If the demo above ever stops working, it's probably because twivatar.glitch.me is no longer available.
By the way, I didn't build either of these services, they were both made by other people.
Introducing the easiest way to get a Twitter Profile Image without using the Twitter API:
Using http://avatars.io/
As #AlexB, #jfred says, it doesn't work at all on mobile devices.
And it's quite a hard way to get a redirected URL using common frameworks like PHP or JavaScript in your single page.
Simply call http://avatars.io/twitter/ruucm at your image tag, like
<img src="https://avatars.io/twitter/ruucm" alt="twt_profile" border="0" width="259"/>
I've tested it with Angular 2+ and it works without any problem.
As of February 20, 2020 it would appear this is impossible. Using the API seems like the only option at the moment. For more info see my question I've opened here: Twitter profile picture images now blocked on most domains
Based on the answer by #Cristiana214
The following PHP snippet can be used to make the https://twitter.com/[screen_name]/profile_image?size=normal trick work on mobile.
Due to twitters redirect to the mobile version of the site links such as https://twitter.com/[screen_name]/profile_image?size=normal get broken on mobile devices
So the script gets the redirect response (to the user avatar) extracts the address then redirects the page itself
if (!isset($_GET['id'])) $_GET['id'] = 'twitter';
$urlget = curl_init();
curl_setopt($urlget, CURLOPT_URL, 'https://twitter.com/' . $_GET['id'] . '/profile_image?size=normal');
curl_setopt($urlget, CURLOPT_HEADER, true);
curl_setopt($urlget, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($urlget);
preg_match_all("/location: (.*)/", $res, $found);
header('Location: ' . $found[1][0]);
So this could be accesses as twitteravatar.php?id=twitter which (at time of writing) reloads to https://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I_normal.jpg
Not pretty but works.
You can get it using the users/show method of the Twitter API -- it does exactly what you described. You give it a the ID or the screen name, and it returns a bunch of data, including profile_image_url.
I found such a solution with C#:
public string Text_toTextFinder(string text, string Fromhere, string Here)
{
int start = text.IndexOf(Fromhere) + Fromhere.Length;
int finish = text.IndexOf(Here, start);
return text.Substring(start, finish - start);
}
string getPhotoURL(string UserName, string size ="x96")
{
using (WebClient client = new WebClient())
{
client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
string htmlCode = client.DownloadString("https://twitter.com/" + UserName);
return Text_toTextFinder(Text_toTextFinder(htmlCode, "<td class=\"avatar\">", "</td>"), "src=\"", "\"").Replace("normal",size);
}
}
For use:
MessageBox.Show(getPhotoURL("screen_name")); //size = 96x96
MessageBox.Show(getPhotoURL("screen_name","normal"));
MessageBox.Show(getPhotoURL("screen_name","200x200"));
MessageBox.Show(getPhotoURL("screen_name","400x400"));
There is no way to do that. In fact Twitter doesn't provide a url to do that like facebook does ( https://graph.facebook.com//?fields=picture)
The issue is report but the status is: 'WontFix', take a look:
https://code.google.com/p/twitter-api/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Stars%20Type%20Bug%20Status%20Summary%20Opened%20Modified%20Component&groupby=&sort=&id=242#makechanges
Well I'm using a tricky way via PHP Dom Parser
include('simple_html_dom.php');
$html = file_get_html('http://twitter.com/mnckry');
$img = array();
foreach($html->find('img.size73') as $e)
$img[] = $e->src;
foreach($html->find('.profile-header-inner') as $e)
$img[] = str_replace("')", "", str_replace("url('", "", $e->{'data-background-image'}));
echo $img[0];//Avatar
echo "<br>";
echo end($img);//ProfileBG
This will give you something like this;
https://pbs.twimg.com/profile_images/378800000487958092/e04a191de329fcf8d000ca03073ad594_bigger.png
to get 2 other size; for big version remove, "_bigger" for smaller version replace "_bigger" with "_normal"
With version 1.1, use
http://a0.twimg.com/profile_images/XXXXX/afpecvf41m8f0juql78p_normal.png
where XXXXX is the User Id
I want to display the tweets of an account in my website. The problem is that the tweets appear always with the format http://t.co/..., instead of the full link as desired by me.
For instance, I obtain:
the rules of the game are all implemented - local players can play together in this link: http://t.co/Nf7j4TaB
if you are very curious... then, here is the link to the xodul's section under development: http://t.co/6Zbti36T
etc...
and I want that these tweets appear like this:
the rules of the game are all implemented - local players can play together in this link: http://xodul.com/tests/js/
if you are very curious... then, here is the link to the xodul's section under development: http://xodul.com/tests
etc...
To make my application I've followed the instructions from:
Simplest PHP example for retrieving user_timeline with Twitter API version 1.1 (from here we can get the text of each tweet, with the links coming in the format: http://t.co/...)
Rendering links in tweet when using Get Statuses API 1.1 (the code of the highest scored answer, in this link replaces, for instance, the text "http://t.co/Nf7j4TaB" with the hyperlink "<a target='_blank' href='http://t.co/Nf7j4TaB'>http://t.co/Nf7j4TaB</a>")
I appreciate very much any help on how to render the twitter's links!
With the tutorial you followed you can use these attributes to show actual link.
Note: In API v1.1, entities will always be included unless you set include_entities to False or 0.
The urls entity
An array of URLs extracted from the Tweet text. Each URL entity comes with the following attributes:
url: The URL that was extracted
display_url: (only for t.co links) Not a URL but a string to display instead of the URL
expanded_url: (only for t.co links) The fully resolved URL
indices: The character positions the URL was extracted from
https://dev.twitter.com/docs/tweet-entities
JavaScript only solution for now to get Twitter posts on your site without using new 1.1 API and actually returns the full url in posts, not the twitter shortened version :-) http://goo.gl/JinwJ
Thank you for your answers.
After analyzing the JSON in the suggested link (https://dev.twitter.com/docs/tweet-entities), I wrote a solution to the exposed problem:
// ...
$twitter_data = json_decode($json); // last line of the code in: http://stackoverflow.com/questions/12916539
// print the tweets, with the full URLs:
foreach ($twitter_data as $item) {
$text = $item->text;
foreach ($item->entities->urls as $url) {
$text = str_replace($url->url, $url->expanded_url, $text);
}
echo $text . '<br /><br />';
// optionally, here, the code from: http://stackoverflow.com/questions/15610968/
// can be added, too.
}
I am working on a website that allows the user to search for the top ten twitter trends in a city or country. At first I was only relying on Twitter's Rest API, but I was having a lot of rate limit issues (at school my rate limit disappears faster than I have a chance to use it). I know that authenticating my API calls will help me to better deal with this issue (Authenticated API calls are charged to the authenticating user’s limit while unauthenticated API calls are deducted from the calling IP address’ allotment).
I implemented #abraham's PHP library (https://github.com/abraham/twitteroauth), unfortunately my API calls aren't being authenticated. I know I have implemented #abraham's PHP library, because it prints out my user information at the end like it should. I have my twitter trend search underneath it but the API call isn't being authenticated. I am not sure how to fix this, and any help would really be appreciated!
This is what I use to get the top ten trends by country:
function showContent(){
// we're going to point to Yahoo's APIs
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// the following code should only run if we've submitted a form
if(isset($_REQUEST['location']))
{
// set a variable named "location" to whatever we passed from the form
$location = $_REQUEST['location'];
// Form YQL query and build URI to YQL Web service in two steps:
// first, we show the query
$yql_query = "select woeid from geo.places where text='$location'";
// then we combine the $BASE_URL and query (urlencoded) together
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
//var_dump($location);
// show what we're calling
// echo $yql_query_url;
// Make call with cURL (curl pulls webpages - it's very common)
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
// Confirm that results were returned before parsing
if(!is_null($phpObj->query->results)){
// Parse results and extract data to display
foreach($phpObj->query->results as $result){
//var_dump($result);
$woeid = $result[0]->woeid;
if (is_numeric ($location))
{
echo "<span style='color:red; padding-left: 245px;'>Please enter a city or a country</span>";
}
else if(empty($result)){
echo "No results found";
}
else {
/* echo "The woeid of $location is $woeid <br />"; */
}
}
}
$jsontrends=file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json");
$phpObj2 = json_decode($jsontrends, true);
echo "<h3 style='margin-top:20px'>TRENDS: ".$phpObj2[0]['locations'][0]['name']."</h3> \r\n";
$data = $phpObj2[0]['trends'];
foreach ($data as $item) {
echo "<br />".$item['name']."\r\n";
echo "<br /> \r\n";
}
if(empty($item)){
echo "No results found";
}
}
}
I then add it to #abraham's html.inc file (along with some php to see the rate limit status) and html.inc is included in the index.php:
<h1>Top Twitter Trends</h1>
<form name='mainForm' method="get">
<input name='location' id='location' type='text'/><br/>
<button id='lookUpTrends'>Submit</button>
</form>
<?php showContent();
$ratelimit = file_get_contents("http://api.twitter.com/1/account/rate_limit_status.json");
echo $ratelimit;
?>
</div>
#abraham's index.php file has some example calls, and since my call doesn't look like this I think that is probably why it isn't being authenticated.
/* Some example calls */
//$connection->post('statuses/update', array('status' => date(DATE_RFC822)));
//$connection->post('statuses/destroy', array('id' => 5437877770));
//$connection->post('friendships/create', array('id' => 9436992));
//$connection->post('friendships/destroy', array('id' => 9436992));
Please help me find what I need to fix so that my API calls are authenticated.
update 10-21
I think in order to make an authenticated API call I need to include something like this is my code:
$connection->get('trends/place', array('id' => $woeid));
It didn't fix my problem, but maybe it is on the right track?
First off, you'll find that keeping your PHP and HTML separate will really help streamline your code and keep logical concerns separate (aggregating the data and displaying it are two different concerns)(many PHPers like MVC).
The code you have shared appears to be correct. My guess is that the issue lies in the creation of the OAuth connection, which should look something like:
<?php
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token,$secret);
Where CONSUMER_KEY and CONSUMER_SECRET are from your Trends Test app and $token and $secret are from the user signing in to twitter and allowing your app permission. Are all these values showing up when you create the TwitterOAuth object?
Also, be sure you update the config items in the twitteroauth.php file (specifically line 21 should be set to use the 1.1 API and line 29 should be set to 'json').
I am trying to write some code in php to show on a website exactly how many times a particular url has been tweeted on Twitter.
I assume I use the info in this page;
http://api.tweetmeme.com/url_info?url=http://dori.co.nz/
But what code would I need to add to the header of a Wordpress theme to call those values?
Many thanks in advance!
<?php
$url = "http://api.tweetmeme.com/url_info?url=http://dori.co.nz/";
$test = file_get_contents($url);
$xml = simplexml_load_string($test);
echo $xml->story->url_count;
?>
Here we go.