Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: jonhurlock/Twitter-Application-Only-Authentication-OAuth-PHP
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: master
Choose a base ref
...
head repository: samtuke/Twitter-Application-Only-Authentication-OAuth-PHP
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
  • 3 commits
  • 4 files changed
  • 1 contributor

Commits on Oct 9, 2014

  1. Making composer packagewq

    samtuke committed Oct 9, 2014
    Copy the full SHA
    3e15f72 View commit details
  2. Renamed Oauth to TwitterSearch.php

    Made TwitterSearch.php Object Oriented
    Moved example logic out of class file
    Added minimal unit test case to check connectivity
    samtuke committed Oct 9, 2014
    Copy the full SHA
    3f5a398 View commit details
  3. Copy the full SHA
    a976530 View commit details
Showing with 199 additions and 131 deletions.
  1. +0 −131 Oauth.php
  2. +155 −0 TwitterSearch.php
  3. +36 −0 TwitterSearchTest.php
  4. +8 −0 composer.json
131 changes: 0 additions & 131 deletions Oauth.php

This file was deleted.

155 changes: 155 additions & 0 deletions TwitterSearch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
<?php

/**
* Oauth.php
*
* Created by Jon Hurlock (@jonhurlock) 2013-03-20.
* Extended by Sam Tuke (@samtuke) on 2014-10-09.
*
* Jon Hurlock's Twitter Application-only Authentication App by Jon Hurlock
* is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
* Permissions beyond the scope of this license may be available at http://www.jonhurlock.com/.
*/

class TwitterSearch
{
// url to send data to for authentication
const AUTH_URL = 'https://api.twitter.com/oauth2/token';
const SEARCH_URL = 'https://api.twitter.com/1.1/search/tweets.json';
CONST INVALIDATE_AUTH_URL = 'https://api.twitter.com/oauth2/invalidate_token';

/**
* @brief Authenticate a session with Twitter using OAuth
* @param string $consumerKey Your personal key from Twitter
* @param string $consumerSecret Your personal secret from Twitter
* @note https://dev.twitter.com/docs/auth/application-only-auth
*/
function authenticate( $consumerKey, $consumerSecret )
{
$this->consumerKey = $consumerKey;
$this->consumerSecret = $consumerSecret;
// Step 1
// step 1.1 - url encode the consumer_key and consumer_secret in accordance with RFC 1738
$encoded_consumer_key = urlencode($this->consumerKey);
$encoded_consumer_secret = urlencode($this->consumerSecret);
// step 1.2 - concatinate encoded consumer, a colon character and the encoded consumer secret
$bearer_token = $encoded_consumer_key.':'.$encoded_consumer_secret;
// step 1.3 - base64-encode bearer token
$base64_encoded_bearer_token = base64_encode($bearer_token);
// step 2
$headers = array(
"POST /oauth2/token HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: jonhurlock Twitter Application-only OAuth App v.1",
"Authorization: Basic ".$base64_encoded_bearer_token."",
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
"Content-Length: 29"
);

$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL, SELF::AUTH_URL); // set url to send to
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
curl_setopt($ch, CURLOPT_POST, 1); // send as post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials"); // post body/fields to be sent
$header = curl_setopt($ch, CURLOPT_HEADER, 1); // send custom headers
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response = curl_exec ($ch); // execute the curl
curl_close($ch); // close the curl
$output = explode("\n", $response);
$bearer_token = '';

foreach ( $output as $line ) {
if ( $line === false ) {
// there was no bearer token
} else {
$bearer_token = $line;
}
}

// decode token
$bearer_token = json_decode( $bearer_token );

// set token for reuse
$this->token = $bearer_token->{'access_token'};
}

/**
* @brief Invalidate the Bearer Token, end the session
* @note should the bearer token become compromised or need to be invalidated for any reason, call this method/function.
*/
function unauthenticate ()
{
$encoded_consumer_key = urlencode($this->consumerKey);
$encoded_consumer_secret = urlencode($this->consumerSecret);
$consumer_token = $encoded_consumer_key.':'.$encoded_consumer_secret;
$base64_encoded_consumer_token = base64_encode($consumer_token);

// step 2
$headers = array(
"POST /oauth2/invalidate_token HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: jonhurlock Twitter Application-only OAuth App v.1",
"Authorization: Basic ".$base64_encoded_consumer_token."",
"Accept: */*",
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".(strlen($this->token)+13).""
);

$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL, SELF::INVALIDATE_AUTH_URL); // set url to send to
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
curl_setopt($ch, CURLOPT_POST, 1); // send as post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
curl_setopt($ch, CURLOPT_POSTFIELDS, "access_token=".$this->token.""); // post body/fields to be sent
$header = curl_setopt($ch, CURLOPT_HEADER, 1); // send custom headers
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$retrievedhtml = curl_exec ($ch); // execute the curl
curl_close($ch); // close the curl

return $retrievedhtml;
}

/**
* @brief search for tweets with a given term
* @param string $query Search term to look for (needle)
* @param string $result_type Twitter compatible result type filter
* @param int $count Limit for tweets to return
* @return StdClass parsed from JSON with array of statuses ($returned->statuses[1])
* @note on https://dev.twitter.com/docs/api/1.1/get/search/tweets
*/
function search( $query, $result_type='mixed', $count='15' )
{
$q = urlencode(trim($query)); // query term
$formed_url ='?q='.$q; // fully formed url

// result type - mixed(default), recent, popular
if ( $result_type!='mixed' ) {
$formed_url = $formed_url.'&result_type='.$result_type;
}

// results per page - defaulted to 15
if( $count!='15' ) {
$formed_url = $formed_url.'&count='.$count;
}

$formed_url = $formed_url.'&include_entities=true'; // makes sure the entities are included, note @mentions are not included see documentation
$headers = array(
"GET /1.1/search/tweets.json".$formed_url." HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: jonhurlock Twitter Application-only OAuth App v.1",
"Authorization: Bearer ".$this->token."",
);

$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL,SELF::SEARCH_URL.$formed_url); // set url to send to
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
$response = curl_exec ($ch); // execute the curl
curl_close($ch); // close the curl

$decoded = json_decode( $response );

return $decoded;
}
}
36 changes: 36 additions & 0 deletions TwitterSearchTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

require_once( 'TwitterSearch.php' );

class TestTwitter extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->twitter = new twitterSearch();
}

public function testSearch()
{
// authenticate using OAuth creds
$this->twitter->authenticate( 'xlN7UWnd2FLWp4oxrtAA', 'nywpCALJ3ZXnlHnPwdGRmnu0jIqAbUBHhauPRCuPzMM' );

// search for the word 'test'
$result = $this->twitter->search( "test" );

// check that results were returned
$this->assertTrue( !empty( $result ) );

// check that tweets were found
$this->assertTrue( $result->statuses > 5 );

// invalidate the token
$this->twitter->unauthenticate();
}

/**
*
*/
public function tearDown()
{
}
}
8 changes: 8 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "samtuke/Twitter-Application-Only-Authentication-OAuth-PHP",
"autoload": {
"psr-0" : {
"samtuke\\Twitter-Application-Only-Authentication-OAuth-PHP" : "src"
}
}
}