Skip to content

Instantly share code, notes, and snippets.

@sunlee-newyork
Created February 21, 2014 18:48
Show Gist options
  • Save sunlee-newyork/9140677 to your computer and use it in GitHub Desktop.
Save sunlee-newyork/9140677 to your computer and use it in GitHub Desktop.
50Tweets // Twitter OAuth APP
<?php
require("twitteroauth/twitteroauth.php");
session_start();
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth('Qsa1aT0cuqarOH45nJp9Jw', 'wivzv9Up61ot08dUbZYf9d22RTEYJBYdEJWbPwM');
// Request authentication tokens and provide redirect URL
$request_token = $twitteroauth->getRequestToken('http://localhost/twitter_oauth.php');
// Save token and secret requests to SESSION
$_SESSION['oauth_token' ] = $request_token['oauth_token' ];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// If success:
if($twitteroauth->http_code==200){
// Generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
// If not, error.
die('Something wrong happened.');
}
?>
<?php
require('twitteroauth/twitteroauth.php');
session_start();
// Brought header up to front because stackoverflow says cannot have any output before header.
// To trigger header correctly I put it inside conditional, with $_SESSION['session'] set after verification
// Maybe this is causing twitter_search.php to come up blank?
if(isset($_SESSION['username'])) {
header('Location: twitter_search.php');
exit();
}
// If all needed SESSIONS are set:
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){
// Success, proceed
$twitteroauth = new TwitterOAuth('Qsa1aT0cuqarOH45nJp9Jw', 'wivzv9Up61ot08dUbZYf9d22RTEYJBYdEJWbPwM', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
// Use verifier to request the access token
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
// Save access token to SESSION
$_SESSION['access_token'] = $access_token;
// Get user's info
$user_info = $twitteroauth->get('account/verify_credentials');
} else {
// Error, go back to login
header('Location: twitter_login.php');
}
// Connect to DB
define('HOST', "localhost");
define('USER', "root" );
define('PASS', "" );
define('DB' , "test" );
error_reporting(E_ERROR);
$connection = mysql_connect(HOST, USER, PASS);
if (!$connection) { die('<H3>=/= Server</H3>: ' . mysql_error()); }
mysql_select_db(DB) or die ("<H3>=/= Database</H3>");
array_walk_recursive($_GET , "mysql_real_escape_string");
array_walk_recursive($_POST, "mysql_real_escape_string");
// Find user by ID
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'twitter' AND oauth_uid = " .$user_info->id);
$result = mysql_fetch_array($query);
// If not find, add to DB
if(empty($result)){
$query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username, oauth_token, oauth_secret) VALUES ('twitter', {$user_info->id}, '{$user_info->screen_name}', '{$access_token['oauth_token']}', '{$access_token['oauth_token_secret']}')");
$query = mysql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
// Otherwise, update the tokens
$query = mysql_query("UPDATE users SET oauth_token = '{$access_token['oauth_token']}', oauth_secret = '{$access_token['oauth_token_secret']}' WHERE oauth_provider = 'twitter' AND oauth_uid = {$user_info->id}");
}
// Set SESSIONS
$_SESSION['id' ] = $result['id' ];
$_SESSION['username' ] = $result['username' ];
$_SESSION['oauth_uid' ] = $result['oauth_uid' ];
$_SESSION['oauth_provider'] = $result['oauth_provider'];
$_SESSION['oauth_token' ] = $result['oauth_token'];
$_SESSION['oauth_secret' ] = $result['oauth_secret'];
echo "<script>location.reload();</script>";
?>
<?php
// FINALLY PASSES SEARCH THROUGH TO TWITTER, THROWS BEAUTIFUL ERROR FROM TWITTER \\
require 'twitteroauth/twitteroauth.php';
session_start();
// If user SESSION is set:
if(!empty($_SESSION['username'])) {
// echo "Session started<br/>";
// echo "OAuth Token: &nbsp;" .$_SESSION['oauth_token']. "<br/>";
// echo "OAuth Secret: &nbsp;" .$_SESSION['oauth_secret'];
$twitteroauth = new TwitterOAuth('Qsa1aT0cuqarOH45nJp9Jw', 'wivzv9Up61ot08dUbZYf9d22RTEYJBYdEJWbPwM', $_SESSION['oauth_token'], $_SESSION['oauth_secret']);
} else {
echo "Session failed";
}
?>
<html>
<head>
<style type="text/css">
#form {
width:500px;
text-align:center;
margin-top:100px;
margin-left:auto;
margin-right:auto;
}
#result {
width:800px;
margin-top:50px;
margin-left:auto;
margin-right:auto;
}
</style>
</head>
<body>
<div id="form"> Enter Your Search Word Here <br><br>
<form action="twitter_search.php" name="form" method="post">
<input type="text" id="search" name="search" />
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</div>
<div id="result">
<?php
// If POSTed successfully:
if($_POST) {
// Assign search word
$search = $_POST['search'];
echo "You looked up: \"".$search."\"<br/>";
// Twitter API request with search word (ONLY tweets in English, are recent, up to 50)
$result = $twitteroauth->get('search/tweets', array(
'q' => $search,
'lang' => 'en',
'result_type' => 'recent',
'count' => 50
));
// If result returns successfull:
if(!empty($result)) {
echo "Here are the 50 most recent tweets:<br/><br/>";
} else {
echo "Search failed.";
}
// Print image results
for($i=0; $i<count($result->statuses); $i++) {
// If tweet has media entity:
if(!empty($result->statuses[$i]->entities->media)) {
// Specifically image entity:
if($result->statuses[$i]->entities->media[0]->type == "photo") {
// Assign URL for <img> tag and echo result
$url = $result->statuses[$i]->entities->media[0]->media_url;
echo "<img src='$url:thumb'>";
$i++;
}
}
}
echo "<br/><br/>";
// Print text results
for($i=0; $i<count($result->statuses); $i++) {
$j = $i + 1;
echo "<br/>Tweet #". $j .": " .$result->statuses[$i]->text;
echo "<br/>Date :" .$result->statuses[$i]->created_at. "<br/>";
}
}
?>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment