Created
May 9, 2014 20:40
-
-
Save jrobinsonc/ccf0849f6df828d93b02 to your computer and use it in GitHub Desktop.
Get tweets from Twitter API v1.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_twitter_access_token($consumer_key, $consumer_secret) | |
{ | |
$options = array( | |
CURLOPT_POSTFIELDS => array('grant_type' => 'client_credentials'), | |
CURLOPT_HTTPHEADER => array('Authorization: Basic ' . base64_encode($consumer_key . ':' . $consumer_secret)), | |
CURLOPT_HEADER => FALSE, | |
CURLOPT_URL => 'https://api.twitter.com/oauth2/token', | |
CURLOPT_RETURNTRANSFER => TRUE | |
); | |
$curl = curl_init(); | |
curl_setopt_array($curl, $options); | |
$result = curl_exec($curl); | |
curl_close($curl); | |
if (FALSE === $result) | |
return FALSE; | |
$oauth_response = json_decode($result); | |
if (NULL === $oauth_response || !property_exists($oauth_response, 'token_type') || $oauth_response->token_type !== 'bearer') | |
return FALSE; | |
return $oauth_response->access_token; | |
} | |
function get_tweets($handler, $count, $consumer_key, $consumer_secret) | |
{ | |
if ('' === session_id()) | |
session_start(); | |
if (!isset($_SESSION['_twitter_token']) || FALSE === $_SESSION['_twitter_token']) | |
$_SESSION['_twitter_token'] = get_twitter_access_token($consumer_key, $consumer_secret); | |
$options = array( | |
CURLOPT_HTTPHEADER => array('Authorization: Bearer ' . $_SESSION['_twitter_token']), | |
CURLOPT_HEADER => FALSE, | |
CURLOPT_URL => 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $handler . '&count=' . $count, | |
CURLOPT_RETURNTRANSFER => TRUE | |
); | |
$curl = curl_init(); | |
curl_setopt_array($curl, $options); | |
$result = curl_exec($curl); | |
curl_close($curl); | |
return json_decode($result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment