Last active
May 22, 2016 17:01
-
-
Save kopiro/5781634 to your computer and use it in GitHub Desktop.
Get Tweets in PHP with OAUTH2
This file contains hidden or 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 buildBaseString($baseURI, $method, $params) { | |
| $r = array(); | |
| ksort($params); | |
| foreach($params as $key=>$value){ | |
| $r[] = "$key=" . rawurlencode($value); | |
| } | |
| return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r)); | |
| } | |
| function buildAuthorizationHeader($oauth) { | |
| $r = 'Authorization: OAuth '; | |
| $values = array(); | |
| foreach($oauth as $key=>$value) | |
| $values[] = "$key=\"" . rawurlencode($value) . "\""; | |
| $r .= implode(', ', $values); | |
| return $r; | |
| } | |
| function getTweets($user) { | |
| try { | |
| $url = "https://api.twitter.com/1.1/statuses/user_timeline/".$user.".json"; | |
| $oauth_access_token = ""; | |
| $oauth_access_token_secret = ""; | |
| $consumer_key = ""; | |
| $consumer_secret = ""; | |
| $oauth = array( | |
| 'oauth_consumer_key' => $consumer_key, | |
| 'oauth_nonce' => time(), | |
| 'oauth_signature_method' => 'HMAC-SHA1', | |
| 'oauth_token' => $oauth_access_token, | |
| 'oauth_timestamp' => time(), | |
| 'oauth_version' => '1.0' | |
| ); | |
| $base_info = buildBaseString($url, 'GET', $oauth); | |
| $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret); | |
| $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true)); | |
| $oauth['oauth_signature'] = $oauth_signature; | |
| $header = array(buildAuthorizationHeader($oauth), 'Expect:'); | |
| $options = array( | |
| CURLOPT_HTTPHEADER => $header, | |
| CURLOPT_HEADER => false, | |
| CURLOPT_URL => $url, | |
| CURLOPT_RETURNTRANSFER => true, | |
| CURLOPT_SSL_VERIFYPEER => false); | |
| $feed = curl_init(); | |
| curl_setopt_array($feed, $options); | |
| $json = curl_exec($feed); | |
| curl_close($feed); | |
| $twitter_data = json_decode($json, true); | |
| if (isset($twitter_data['errors'])) return ''; | |
| return $twitter_data; | |
| } catch (Exception $e) { | |
| return ''; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment