views:

284

answers:

1

I am using abraham williams library to update twitter status using oauth. But I am constantly getting 'session expired' error. How can I get around this. This is my source.

connect.php

<?php
session_start();
require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "--------------------");
define("CONSUMER_SECRET", "---------------------------");

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken('http://127.0.0.1/callback.php');

$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] =
$request_token['oauth_token_secret'];

$url = $connection->getAuthorizeURL($request_token);
header('Location: ' . $url);
?>

index.php

<?php
session_start();

if (empty($_SESSION['access_token'])) {
header('Location: ./connect.php');
}

require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "---------------");
define("CONSUMER_SECRET", "--------------------------------");

$connection = new TwitterOAuth(
  CONSUMER_KEY,
  CONSUMER_SECRET,
  $_SESSION['access_token']['oauth_token'],
  $_SESSION['access_token']['oauth_token_secret']
);

include("form.php");
$msg = $_POST['tweet'];

if (!empty($msg)) {
  $tweetmsg = $msg; }
else {
  exit('Post a tweet');
     }

$result = $connection->post('statuses/update', array('status' => $tweetmsg));
unset($_SESSION['tweetmsg']);
if (200 === $connection->http_code) {
   echo'tweet posted';
}
else {
$resultmsg = 'Could not post Tweet. Error: '.$httpCode.'  
Reason:'.$result->error;
echo $resultmsg;
}
?>

callback.php

<?php
session_start();
require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "---------------");
define("CONSUMER_SECRET", "------------------------------");

if (
  isset($_REQUEST['oauth_token'])
  && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']
) {
  //echo 'Session expired';
header('Location: ./connect.php');
}
else {
  $connection = new TwitterOAuth(
    CONSUMER_KEY,
    CONSUMER_SECRET,
    $_SESSION['oauth_token'],
    $_SESSION['oauth_token_secret']
  );
  $_SESSION['access_token'] =
$connection->getAccessToken($_REQUEST['oauth_verifier']);
header('Location: index.php');

unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
}
?> 
A: 

callback.php is designed to be used once during each negotiation for an access token. Not each time you want to tweet.

I recommend breaking your code into the following three files:

connect.php

<?php
session_start();
require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "--------------------");
define("CONSUMER_SECRET", "---------------------------");

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken('http://127.0.0.1/callback.php');

$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] =
$request_token['oauth_token_secret'];

$url = $connection->getAuthorizeURL($request_token);
header('Location: ' . $url);

callback.php

<?php
session_start();
require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "------------------");
define("CONSUMER_SECRET", "----------------------------");

if (
  isset($_REQUEST['oauth_token']) 
  && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']
) {
  echo 'Session expired';
}
else {
  $connection = new TwitterOAuth(
    CONSUMER_KEY,
    CONSUMER_SECRET,
    $_SESSION['oauth_token'],
    $_SESSION['oauth_token_secret']
  );
  $_SESSION['access_token'] = $connection->getAccessToken($_REQUEST['oauth_verifier']);
  header('Location: index.php');
}

index.php

<?php
session_start();

if (empty($_SESSION['access_token'])) {
  if (!empty($_POST['tweetmsg'])) {
    $_SESSION['tweetmsg'] = $_POST['tweet'];
  }
  header('Location: ./connect.php');
}

require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "------------------");
define("CONSUMER_SECRET", "----------------------------");

$connection = new TwitterOAuth(
  CONSUMER_KEY,
  CONSUMER_SECRET,
  $_SESSION['access_token']['oauth_token'],
  $_SESSION['access_token']['oauth_token_secret']
);

if (!empty($_POST['tweetmsg'])) {
  $tweetmsg = $_POST['tweetmsg'];
} elseif (!empty($_SESSION['tweetmsg'])) {
  $tweetmsg = $_SESSION['tweetmsg'];
} else {
  exit('No tweet value in session or from form');
}

$result = $connection->post('statuses/update', array('status' => $tweetmsg));
unset($_SESSION['tweetmsg']);
if (200 === $connection->http_code) {
  $resultmsg = 'Tweet Posted: '.$tweetmsg;
}
else {
  $resultmsg = 'Could not post Tweet. Error: '.$httpCode.' Reason: '.
  $result->error;
}
abraham
thanX 4 the response abraham :-)
XCeptable
thanX 4 the response abraham :-) I break the application exactly as you mentioned, now it raises this error: 'Could not post Tweet. Error: 401 Reason: Could not authenticate you'. One more question is as in ur recommended breakup, there is no method to send user to Twitter for authentication so how will this work. As my application is to be used by many users to post updates to their twitter accounts.
XCeptable
You still have to get a request token and send the user to Twitter. I updated my response to include connect.php and a check in index.php to see if there there is an access token in the session.
abraham
thank you very much abraham ... I updated the code. But now when I press authenticate button on Twitter, the error message from Twitter appears, 'Sorry, that page doesn’t exist!'.
XCeptable
What is the Twitter URL you land on?
abraham
XCeptable
So you get redirected to Twitter ok? You authorize' the application to access your Twitter account then you get the "page doesn't exist" error? Make sure you have the callback URL set properly in $request_token = $connection->getRequestToken('http://127.0.0.1/callback.php');. If should be the same URL as where you access index.php just with callback.php instead.
abraham
XCeptable
I tweaked the code a little bit. Most of the edits were after your issue however. If it still does not work then I think something is wrong with how your server handles sessions. The if that checks returns "session expired" only checks to make sure the oauth_token you return from twitter matches the existing one in the session.
abraham
Yes, the problem still persists. I am using apache 2.2.14 (IPV6 enabled) web server on windows 7. What can be workaround for it. I commented the if condition for session check, it for once work. And after that again started giving session expire error.
XCeptable
XCeptable
Glad to hear you got it working. It looks like stale session data was causing issues.
abraham
I have one question, I have to upload it on a server and it has to be used by many people. I have only experience of single user applications. The $tweetmsg will contain message that is 2B twitted by a user. For single user its fine but what when many people have opened application from server.
XCeptable
If they users are tweeting whatever they want you will have to create an HTML form and submit it to the script filling $tweetmsg with whatever they wish to tweet.
abraham
Also if my reply was the solution you were looking be sure to mark it as the correct answer.
abraham
XCeptable
"stdClass Object ( [request] => /1/statuses/update.json [error] => Client must provide a 'status' parameter with a value. )". I have a strange problem. I call index.php from HTML form in index.php, its empty. Can you kindly look at index.php to see why the value passed vanished reaching here. Otherwise its working this way as I checked by assigning value in index file.
XCeptable
XCeptable
Try `$tweetmsg = $_POST['tweet'];` and make the textarea input id/name is `tweet`. If that does not work try `$tweetmsg = $_REQUEST['tweet'];`.
abraham
XCeptable
I even tried to use session variable here but exactly same behavior is shown by session variable too like. $tweetmsg = $_REQUEST['tweet'];$_SESSION['tweetmsg'] = $tweetmsg; --------------------------------- $result=$connection->post('statuses/update',array('status'=> $_SESSION['tweetmsg']));
XCeptable
$_POST is not persistent storage. If you have a user POST a form to index.php and there is no accesss_token in session they will be sent to Twitter to authenticate. When this happens the $_POST data is discarded. Either have the user authenticate before displaying a form to them or save the $_POST data in a session for when they get back from twitter.com.
abraham
@$_POST is not persistent storage..... I had think on it, is not it strange as I save the value in a local variable that is $tweetmsg " statement as its not necessary to get value at start. But No value is passed here from $_POST.
XCeptable
Unless you save it to $_SESSION or have the user resubmit the form the variables are discarded between page loads. $tweetmsg is not saved between page loads. here is some more information on sessions: http://www.phpro.org/tutorials/Introduction-To-PHP-Sessions.html
abraham
I have tried storing $tweetmsg value in session variable but it behaves exactly same as local variable $tweetmsg i.e. lost value after page load. If you kindly look at my edited index.php source above, it is how I am using session variable to store $teetmsg value.
XCeptable
My guess is that since when you return from twitter.com $_POST['tweet'] is a null value it is overwriting the stored $_SESSION['tweetmsg'] with that null value.
abraham
XCeptable
XCeptable
if (!empty($_POST['tweetmsg'])) { $tweetmsg = $_POST['tweetmsg']; } else { $tweetmsg = $_SESSION['tweetmsg']; }
abraham
I now just tried this one before reading ur message, but it gave same result. Here is code what I tried "if(!empty($_REQUEST['tweet'])){ $_SESSION['tweetmsg'] = $_REQUEST['tweet']; //print $_SESSION['tweetmsg']; } else { $msg = $_SESSION['tweetmsg']; }if (empty($_SESSION['access_token'])) {header('Location: ./connect.php');}echo $msg;//session_unset();"
XCeptable
I edited the index.php too for easy readability.
XCeptable
XCeptable
As long as the users cookie is valid and the session has not expired the session data will be there. Going to twitter.com will not change that.
abraham
I edited the index.php in my answer. Have a look at that.
abraham
exit('No tweet value in session or from form');
XCeptable
the problem is after "header('Location: ./connect.php');" $_SESSION['tweetmsg'] looses its value strangely. I check by "if(isset($_SESSION['tweetmsg'])) {echo"set";} else echo"no set"; results 'no set'-
XCeptable
I tried to pass value through setcookie() but cookie donot exist after page reload. If setting cookies is problem than session variables may be are suffering bec of it. I edited the index.php, see it to validate the test that I did.
XCeptable
Sessions are working properly. If they were not authentication would never work and nothing would ever get tweeted. If you save a value to `$_SESSION['tweetmsg']` before `header('Location: ./connect.php');` then upon returning to `index.php` `$_SESSION['tweetmsg']` will still have a value.
abraham
Yes, you are right. This thing came into my mind but 4get for the time being wehn SetCookie was not set. But then why $_SESSION['tweetmsg'] results in 'not-set' after page reloaded by header. Can you give any clue I could work on as I am not finding any reason still.
XCeptable
XCeptable
XCeptable
I don't understand what you are asking. If you log out of twitter.com it does not effect your application. Once your applications session expires you will have to go through the authentication flow with twitter.com again but that will be infrequent and you can configure PHP to extend the amount of time before the session expires.
abraham
XCeptable
XCeptable
Check out the documentation for statuses/update. Specifically for including in_reply_to_status_id. http://dev.twitter.com/doc/post/statuses/update
abraham
How do we get status-id of a specific status update .....
XCeptable
If you have a status object like `$status` it will be the `id` attribute and it would be accessed like `$status->id`.
abraham
XCeptable
Here is information about how replies work: http://support.twitter.com/articles/14023-what-are-replies-and-mentions
abraham

related questions