jrobinsonc
5/9/2014 - 8:40 PM

Get tweets from Twitter API v1.1

Get tweets from Twitter API v1.1

<?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);
}