Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidandorf/f49e9473f3b496728f92 to your computer and use it in GitHub Desktop.
Save davidandorf/f49e9473f3b496728f92 to your computer and use it in GitHub Desktop.
<?php
define('T_API_KEY', '');
define('T_API_TOKEN', '');
echo get_twitter_lookup_data('ladygaga');
function get_twitter_lookup_data($screen_name)
{
//These are our constants.
$api_base = 'https://api.twitter.com/';
$bearer_token_creds = base64_encode(T_API_KEY . ':' . T_API_TOKEN);
//Get a bearer token.
$opts = array('http' => array(
'method' => 'POST',
'header' => 'Authorization: Basic ' . $bearer_token_creds . "\r\n" .
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
'content' => 'grant_type=client_credentials'));
$context = stream_context_create($opts);
$json = file_get_contents($api_base . 'oauth2/token', false, $context);
//echo $json;
$result = json_decode($json, true);
if (!is_array($result) || !isset($result['token_type']) || !isset($result['access_token'])) {
die("Something went wrong. This isn't a valid array: " . $json);
}
if ($result['token_type'] !== "bearer") {
die("Invalid token type. Twitter says we need to make sure this is a bearer.");
}
//Set our bearer token. Now issued, this won't ever* change unless it's invalidated by a call to /oauth2/invalidate_token.
//*probably - it's not documentated that it'll ever change.
$bearer_token = $result['access_token'];
//$bearer_token = 'AAAAAAAAAAAAAAAAAAAAANJzLAAAAAAAwT4xEU67OhC%2FnlsNFDltJdMlB7U%3DiQsQKpAvgQ3joiZbodSlzw6COQwuKQYwwvqEJ7YbtZLrZOwPsi';
//Try a twitter API request now.
$opts = array('http' => array('method' => 'GET', 'header' =>
'Authorization: Bearer ' . $bearer_token));
$context = stream_context_create($opts);
$json = file_get_contents($api_base . '1.1/users/lookup.json?screen_name=' .
urlencode($screen_name) . '&include_entities=true', false, $context);
return ($json);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment