Before i make a call to twitter, I check for the chache version of data. If there is no cache, then i create a connection with twitter.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token);
This is how i have planned to do. I haven't started it yet.
The question is :
Which is best way to do this?
1) Check for the cache, if there is no cache create a new connection and get details from twitter.
2) Create a new connection in top of every file ( or in a header ) check for cache, if there is no cache, (connection is already exists. so) get the details from twitter.
And, How do i check whether the connection ($connection) is active?
The below would roughly do what you're asking for. The example below uses APC
//define cache key
$cacheKey = "twitterResponse[" . md5($endpoint, implode("&", $parameters) . "]";
//attempt to grab from cache
$foundCachedResponse = false;
$twitterResponse = apc_fetch($cacheKey, $foundCachedResponse);
//only when needed
if(!foundCachedResponse){
//twitter connection
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token);
//make the call
$twitterResponse = $connection->getTweetsOrWhatever($parameters);
//cache the response
apc_store($cacheKey, $twitterResponse, 600);
}
//return
return $twitterResponse;
To see if APC is enabled:
if(!extension_loaded('apc')){
die('no APC');
}
Related
Im using abrahams oauth twitter library. but Im having some difficulty posting to twitter from php on my site.
I am receiving zero errors, but nothing is happening. Has anyone been able to solve this very simple issue? Can you share you knowledge?
Thx
/* Load required lib files. */
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('twitteroauth/config.php');
$connection = new TwitterOAuth ('myprivatecode', myprivatecode', 'myprivatecode','myprivatecode');
$content = $connection->get('account/verify_credentials');
$connection->post('statuses/update', array('status' => $myTweet));
Try this,
<?PHP
require_once 'twitteroauth.php';
define("CONSUMER_KEY", "....");
define("CONSUMER_SECRET", "...");
define("OAUTH_TOKEN", "...");
define("OAUTH_SECRET", "...");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('account/verify_credentials');
$connection->post('statuses/update', array('status' => 'test'));
?>
After requesting Read & Write permissions, you have to RECREATE your access tokens to reflect the new permissions.
A working example for Post to twitter using PHP Oauth API
Hope it helps..
" /* Load required lib files. */ session_start();
require_once('twitteroauth/twitteroauth.php'); require_once('twitteroauth/config.php');
$connection = new TwitterOAuth ('myprivatecode', myprivatecode' 'myprivatecode','myprivatecode');
$content = $connection->get('account/verify_credentials'); $connection->post('statuses/update', array('status' => $myTweet)); "
Have you set a variable via a form post or anything for
$mytweet
Without any more information it is hard to tell. I assume the files are correct in the require_once since the file actually processes.
Make sure the form is sent via post, not much else we can help with with so little information.
I want to post some text automatically to my application twitter account. I create an account for that and take all the needed information and write a php code for it. it is simple code:
I made it just to test the post ability :
<?php
require_once 'oauth/twitteroauth.php';
$message = "hiiiiiii"; #actual message to twitter
define("CONSUMER_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("CONSUMER_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
print_r($connection);
$content = $connection->get('account/verify_credentials');
//print_r($content);
$connection->post('statuses/update', array('status' => $message));
?>
I get the information from the account so i think the connection is working but why i can not post any thing? i tried to post this message but after executing this code nothing happened on my twitter no new tweet is shown????
$connection->post is a method :
/**
* POST wrapper for oAuthRequest.
*/
function post($url, $parameters = array()) {
$response = $this->oAuthRequest($url, 'POST', $parameters);
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response);
}
return $response;
}
My first port of call if you are able to receive information from the account using those credentials, would be that your app has read AND write (posting) permissions:
Go to dev.twitter.com/apps. Select your app, then under 'settings' -->
'application type' you will find what you need.
Although that didn't work, no matter what you changed in your code posting to your account through this app wouldn't work as that functionality was outside the permissions you set yourself. So now we know that you're able to post:
Change
$connection->post('statuses/update', array('status' => $message));
To
$result = $connection->post('statuses/update', array('status' => $message));
Then see what the value of $result is. This might provide some clues
Ok so the response is telling you, you still don't have permissions, you need to regenerate your token and access credentials then update your code with them:
define("CONSUMER_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("CONSUMER_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
Those credentials still have the previous permissions attached to them, when you request new token, it will reference the new permissions and allow you to post.
I am connecting to Tumblr (it's the same process as twitter almost identical).
I get all the way through to the verify page, verify the app, then get returned to the previos page, all of the correct stuff is on the querystring but i get a 400 error a bit on the API docs says that this means "invalid input data".
Here's my code:
require("tumblr/tumblroauth/tumblroauth.php");
// Enter your Consumer / Secret Key:
$consumer = $conf['Tumblr']['consumer'];
$secret = $conf['Tumblr']['secret'];
/* Start session and load lib */
if(!isset($_REQUEST['oauth_token']))
{
// Start the Session
session_start();
$connection = new TumblrOAuth($conf['Tumblr']['consumer'], $conf['Tumblr']['secret']);
// this url is correct
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$temporary_credentials = $connection->getRequestToken($url);
$redirect_url = $connection->getAuthorizeURL($temporary_credentials, FALSE);
echo "going to".$redirect_url; // looks good
//have to use this as headers have started
echo '<script>window.location.href="'.$redirect_url.'";</script>';
}
/* If the oauth_token is old redirect to the connect page. */
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
$_SESSION['oauth_status'] = 'oldtoken';
session_destroy();
}
if(isset($_REQUEST['oauth_token']))
{/* Create TumblroAuth object with app key/secret and token key/secret from default phase */
$connection = new TumblrOAuth($consumer, $secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/* Request access tokens from tumblr */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
/* Save the access tokens. Normally these would be saved in a database for future use. */
$_SESSION['access_token'] = $access_token;
/* Remove no longer needed request tokens */
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
/* If HTTP response is 200 continue otherwise send to connect page to retry */
if (200 == $connection->http_code) {
/* The user has been verified and the access tokens can be saved for future use */
$_SESSION['status'] = 'verified';
echo 'connection made heres the code:<br/>'.$connection->http_code;
} else {
/* Save HTTP status for error dialog on connnect page.*/
// THIS IS ALWAYS BEING OUTPUT AT THE END
echo "oh no something is wrong code:<br/>".$connection->http_code;
}
}
Please can someone have a look I feel like I have tried everything on the planet to get this to work..
ps using : https://github.com/jacobbudin/tumblroauth
I think your problem is here
$redirect_url = $connection->getAuthorizeURL($temporary_credentials, FALSE);
Try
$redirect_url = $connection->getAuthorizeURL($temporary_credentials);
and let us know if you're still having trouble
I am using Abraham Williams twitter api in order to log in the user. During step one I store the temporary oauth_token and oauth_token _secret in the session. After the user is redirected to my page after the sign in process the session data stored previously are lost. How can I solve this ?
function oauth()
{
//Build TwitterOAuth object with client credentials
$connection = new TwitterOAuth($this->consumer_key, $this->consumer_secret);
//Get temporary credentials
$request_token = $connection->getRequestToken($this->callback);
//Save temporary credentials to session
$session_data = array(
'oauth_token' => $request_token['oauth_token'],
'oauth_token_secret'=> $request_token['oauth_token_secret'],
);
$this->session->set_userdata($session_data);
//If last connection failed don't display authorization link.
switch ($connection->http_code)
{
case 200:
$url = $connection->getAuthorizeURL($request_token['oauth_token'], TRUE);
header('Location: ' . $url);
break;
default:
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
}
function callback()//callback after user signs in with twitter
{
$connection = new TwitterOAuth($this->consumer_key,
$this->consumer_secret,
$this->session->userdata("oauth_token"),
$this->session->userdata("oauth_token_secret"));
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
$this->session->set_userdata('access_token', $access_token);
//Remove no longer needed request tokens
$this->session->unset_userdata('oauth_token');
$this->session->unset_userdata('oauth_token_secret');
//If HTTP response is 200 continue otherwise send to connect page to retry
if (200 == $connection->http_code)
{
$this->session->set_userdata('twitter_log_in', TRUE);
redirect('/main/', 'refresh');
}
}
Of course you verified you config file in Session section, but:
Already you tried it in other PC?
Tried DB Sessions or the inverse?
Made you simple tests excluding you case (twitter oauth class)
In somehow, maybe the code are replacing the vars, try log the informations in many parts of the code, to see if it as overwrote in the life of the process
Im using the following code to read to consumer_key and consumer_secret from config.php, pass it to twitter and retrieve some bits of information back from them.
What the script below attempts to do is 'cache' the request_token and request_secret. So in theory I should be able to reuse those details (all 4 of them to automatically tweet when required).
<?php
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
$consumer_key = CONSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
if (isset($_GET["register"]))
{
// If the "register" parameter is set we create a new TwitterOAuth object
// and request a token
/* Build TwitterOAuth object with client credentials. */
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request = $oauth->getRequestToken();
$request_token = $request["oauth_token"];
$request_token_secret = $request["oauth_token_secret"];
// At this I store the two request tokens somewhere.
file_put_contents("request_token", $request_token);
file_put_contents("request_token_secret", $request_token_secret);
// Generate a request link and output it
$request_link = $oauth->getAuthorizeURL($request);
echo "Request here: " . $request_link . "";
die();
}
elseif (isset($_GET["validate"]))
{
// This is the validation part. I read the stored request
// tokens.
$request_token = file_get_contents("request_token");
$request_token_secret = file_get_contents("request_token_secret");
// Initiate a new TwitterOAuth object. This time we provide them with more details:
// The request token and the request token secret
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$request_token, $request_token_secret);
// Ask Twitter for an access token (and an access token secret)
$request = $oauth->getAccessToken();
// There we go
$access_token = $request['oauth_token'];
$access_token_secret = $request['oauth_token_secret'];
// Now store the two tokens into another file (or database or whatever):
file_put_contents("access_token", $access_token);
file_put_contents("access_token_secret", $access_token_secret);
// Great! Now we've got the access tokens stored.
// Let's verify credentials and output the username.
// Note that this time we're passing TwitterOAuth the access tokens.
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token, $access_token_secret);
// Send an API request to verify credentials
$credentials = $oauth->oAuthRequest('https://twitter.com/account/verify_credentials.xml', 'GET', array());
// Parse the result (assuming you've got simplexml installed)
$credentials = simplexml_load_string($credentials);
var_dump($credentials);
// And finaly output some text
echo "Access token saved! Authorized as #" . $credentials->screen_name;
die();
}
?>
When i run /?verify&oauth_token=0000000000000000 - It works however trying to resuse the generated tokens etc... I get a 401
Here is the last bit of code where I attempt to reuse the details from Twitter combined with my consumer_key and consumer_secret and get the 401:
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
// Read the access tokens
$access_token = file_get_contents("access_token");
$access_token_secret = file_get_contents("access_token_secret");
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth($consumer_key, $consumer_key_secret,
$access_token, $access_token_secret);
// Post an update to Twitter via your application:
$oauth->OAuthRequest('https://twitter.com/statuses/update.xml',
array('status' => "Hey! I'm posting via #OAuth!"), 'POST');
Not sure whats going wrong, are you able to cache the details or do i need to try something else?
You can't store the OAuth tokens in cache and to more than 1 request with it, as OAuth is there to help make the system secure, your "oauth_token" will contain some unique data, this token will only be able to make one call back to twitter, as soon as the call was made, that "oauth_token" is no longer valid, and the OAuth class should request a new "oauth_token", thus making sure that every call that was made is secure.
That is why you are getting an "401 unauthorized" error on the second time as the token is no longer valid.
twitter is still using OAuth v1 (v2 is still in the draft process even though facebook and google already implemented it in some parts)
The image below describes the flow of the OAuth authentication.
Hope it helps.
A while ago I used this to connect to twitter and send tweets, just note that it did make use of some Zend classes as the project was running on a zend server.
require_once 'Zend/Service/Twitter.php';
class Twitter {
protected $_username = '<your_twitter_username>';
protected $_token = '<your_twitter_access_token>';
protected $_secret = '<your_twitter_access_token_secret>';
protected $_twitter = NULL;
//class constructor
public function __construct() {
$this->getTwitter();
}
//singleton twitter object
protected function getTwitter() {
if (null === $this->_twitter) {
$accessToken = new Zend_Oauth_Token_Access;
$accessToken->setToken($this->_token)
->setTokenSecret($this->_secret);
$this->_twitter = new Zend_Service_Twitter(array(
'username' => $this->_username,
'accessToken' => $accessToken,
));
$response = $this->_twitter->account->verifyCredentials();
if ($response->isError()) {
throw new Zend_Exception('Provided credentials for Twitter log writer are wrong');
}
}
return $this->_twitter;
}
//send a status message to twitter
public function update( $tweet ) {
$this->getTwitter()->status->update($tweet);
}
}
In your second script, it looks like you aren't setting the Consumer Key and Consumer Secret when you create your TwitterOAuth instance.
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);