Skip to content

Instantly share code, notes, and snippets.

@abraham
Created November 20, 2010 09:50
Show Gist options
  • Save abraham/707735 to your computer and use it in GitHub Desktop.
Save abraham/707735 to your computer and use it in GitHub Desktop.
Never have a broken Twitter avatar again
<?php
// Requires the TwitterOAuth library. http://github.com/abraham/twitteroauth
require_once('twitteroauth/twitteroauth.php');
// ACCESS_TOKEN and ACCESS_SECRET are only needed if you want the request to count against a specific users rate limit.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET);
if(!empty($_REQUEST['screen_name']) {
// I'm using users/show but you could also use users/profile_image here.
$connection->get('users/show', array('screen_name' => $_REQUEST['screen_name']));
if($connection->http_code == 200) {
// Update stored user profile.
} else {
// Log error.
}
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Twitter Avatars</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script>
$(function () {
// Attach an error handler to all img elements with the class twitter-avatar.
$('img.twitter-avatar').error(function() {
// Pull the screen_name out of the data attribute.
var screen_name = $(this).attr('data-screen-name');
// Change the image source to the static URL for a users avatar.
this.src='https://api.twitter.com/1/users/profile_image/' + screen_name + '?size=normal';
// Tell the server about the broken image so the persistent storage can be update.
$.ajax({
type: 'POST',
url: '/avatar.php',
data: 'screen_name=' + screen_name
});
});
});
</script>
</head>
<body>
<header>
<h1>Twitter Avatars</h1>
<p class="tagline">Never another broken avatar.</p>
</header>
<section id='content'>
<!-- A class of twitter-avatar and an attribute of data-screen-name set to the users screen_name are needed. -->
<!-- You will notice that the image linked is missing the . before png and so will not load. -->
<img src='http://a0.twimg.com/profile_images/1117369624/new-border_normalpng' class='twitter-avatar' data-screen-name='abraham' width='48' height='48' alt='Twitter avatar' />
</section>
<footer>
</footer>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment