I'm pretty much following this tutorial
http://net.tutsplus.com/tutorials/php/how-to-authenticate-users-with-twitter-oauth/
and i have everything working i can see the screen name when i call it as well as my status time line but for some reason i can not post a status. i have looked everywhere on the internet and everybody does it the same way but i cant get mine to work.
here is my twitter_oauth.php
<?php
require("twitteroauth.php");
session_start();
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){
$twitteroauth = new TwitterOAuth('consumerkey', 'otherkey', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
//request the access token
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
$_SESSION['access_token'] = $access_token;
$user_info = $twitteroauth->get('account/verify_credentials');
//useful for seeing array key names
//print_r($user_info);
mysql_connect('localhost', 'usernamr', 'password');
mysql_select_db(' database_twitter');
if(isset($user_info->error)){
header('Location: twitter_login.php');
}else{
//find the user by its ID
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'twitter' AND oauth_uid = ". $user_info->id);
$result = mysql_fetch_array($query);
//if it doesnt exist add
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{
// 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}");
}
$_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'];
header('Location: twitter_update.php');
}
}else{
header('Location:twitter_login.php');
}
?>
and heres twitter_update.php
<?php
require("twitteroauth.php");
session_start();
?>
<h2>Hello <?php
if(!empty($_SESSION['username'])){
echo '#' .$_SESSION['username'];
}else{
echo 'Guest';
}
if(!empty($_SESSION['username'])){
$twitteroauth = new TwitterOAuth('key', 'key', $_SESSION['oauth_token'], $_SESSION['oauth_secret']);
$status_timeline = $twitteroauth->get('statuses/home_timeline', array('count' => 40));
$content = $twitteroauth->get('account/verify_credentials');
$twitteroauth->get('users/show', array('screen_name' => 'abraham'));
//$twitteroauth->post('statuses/update', array('status' => 'Testing out the twitter api with oauth'));
//print_r($status_timeline);
$twitteroauth->post('statuses/update', array('status' => "hello world"));
}
?>
</h2>
was trying to find out if it has been updated but couldn't find anything and i'm guessing it isn't
You are saving the access_token to $_SESSION['access_token'] in twitter_oauth.php but then in twitter_update.php you are using $_SESSION['oauth_token'].
twitter_oauth.php should also build a new TwitterOAuth object with the access_token before making requests to the API as the user.
You also have no error handling in the event that getting an access token fails.
Related
I'm currently building a survey. I've made quite a bit of progress so far. If a participant completes and submits the survey it successfully enters my database and returns the participant to the main page of my site but if one question is skipped by the participant, when they try to submit the survey it returns a blank display and no data is fed into my database.
I want to create a survey that gives participants the ability to skip questions, and returns them to the homepage after submitting the survey.
I understand it may be easy for some but I'm fairly new to PHP so I'm still learning, please see the code below.
<?php
$radioVal1 = $_POST["q1"];
$radioVal2 = $_POST["q2"];
$radioVal3 = $_POST["q3"];
$radioVal4 = $_POST["q4"];
$radioVal5 = $_POST["q5"];
$checkboxVal6 = $_POST["q6"];
$textAreaVal = $_POST["comment"];
session_start();
require_once('DBConnection.php');
if(isset($_POST["submit_questionnaire"])){
if(isset($_POST["q1"]) && isset($_POST["q2"]) && isset($_POST["q3"]) && isset($_POST["q4"]) && isset($_POST["q5"]) && isset($_POST["q6"]) && $textAreaVal!=null){
echo "blyat";
$username = $_SESSION['username'];
$db = new DBConnection();
$conn= $db::getInstance()->dbConnect();
$query_code = "SELECT id_code FROM users WHERE name = '$username'";
$id_codeRow = $db::getInstance()->selectDB($query_code)->fetch_row();
$id_code = (string)array_values($id_codeRow)[0];
$query = "INSERT INTO questionnaire VALUES (default, '$id_code', '$radioVal1', '$radioVal2', '$radioVal3','$radioVal4', '$radioVal5', '$checkboxVal6', '$textAreaVal')";
$insert_value = $db::getInstance()->selectDB($query);
session_destroy();
header("Location: index.php");
exit();
}
}
// You can remplace "&&" by "OR" so any questions can be skipped by the user but the user have to complete atleast 1 question.
<?php
$radioVal1 = $_POST["q1"];
$radioVal2 = $_POST["q2"];
$radioVal3 = $_POST["q3"];
$radioVal4 = $_POST["q4"];
$radioVal5 = $_POST["q5"];
$checkboxVal6 = $_POST["q6"];
$textAreaVal = $_POST["comment"];
session_start();
require_once('DBConnection.php');
if(isset($_POST["submit_questionnaire"])){
if(isset($_POST["q1"]) OR isset($_POST["q2"]) OR isset($_POST["q3"]) OR isset($_POST["q4"]) OR isset($_POST["q5"]) OR isset($_POST["q6"])){
echo "blyat";
$username = $_SESSION['username'];
$db = new DBConnection();
$conn= $db::getInstance()->dbConnect();
$query_code = "SELECT id_code FROM users WHERE name = '$username'";
$id_codeRow = $db::getInstance()->selectDB($query_code)->fetch_row();
$id_code = (string)array_values($id_codeRow)[0];
$query = "INSERT INTO questionnaire VALUES (default, '$id_code', '$radioVal1', '$radioVal2', '$radioVal3','$radioVal4', '$radioVal5', '$checkboxVal6', '$textAreaVal')";
$insert_value = $db::getInstance()->selectDB($query);
session_destroy();
header("Location: index.php");
exit();
}
}
Trying to safe the Profile img from facebook API. This code will get the url/downloadlink but now I want it to save it somewhere on the server so I can get it out of the database and display it somewhere. I thought I might need to use php copy function but I am not sure. I also already googled it but that are older versions of the facebook API.
$oAuth2Client = $FB->getOAuth2Client();
if (!$accessToken->isLongLived())
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$response = $FB->get("/me?fields=id, first_name, last_name, email,gender,link, birthday,picture.type(large)", $accessToken);
$userData = $response->getDecodedBody();
$fb_foto_url = $userData['picture']['data']['url'];
$voornaam= $app->get_klant_fb($userData['first_name']);
$_SESSION['voornaam'] = $userData['first_name'];
$_SESSION['achternaam'] = $userData['last_name'];
$fb_fotoUrl = $app->saving_fb_foto($userData['picture']['data']['url']);
//data ophalen
$klant= $app->get_klant_fb($userData['id']);
if($klant['id'] > 0) {
//sessie klant zetten
$_SESSION['klant_id'] = $klant['id'];
} else {
//klant aanmaken
unset($query);
$query['oauth_uid'] = $userData['id'];
$query['ledenpagina_id']= $_SESSION['ledenpagina_id'];
$query['voornaam'] = $userData['first_name'];
$query['achternaam'] = $userData['last_name'];
$query['emailadres'] = $userData['email'];
$query['geboortedatum'] = $userData['birthday'];
$query['gender'] = $userData['gender'];
$query['link'] = $userData['link'];
$query['foto'] = $userData['picture']['data']['url'];
$app->insert_query('klanten', $query);
$klant= $app->get_klant_fb($userData['id']);
if($klant['id'] > 0) {
$_SESSION['klant_id'] = $klant['id'];
}
}
I need help how can I convert this code into SDKv4. Cause this code is not working already and giving me redirect loop or something about looping of redirects.
<?php
require '../config.php';
require 'lib/facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => $appID,
'secret' => $appSecret,
));
//get the user facebook id
$user = $facebook->getUser();
if($user){
try{
//get the facebook user profile data
$getUserInfo = $facebook->api('/me');
$params = array('next' => $base_url.'logout.php');
//logout url
$logout =$facebook->getLogoutUrl($params);
}catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
}
if(!empty($user)){
//login url
$userInfo = $getUserInfo;
$_SESSION['ses_id'] = md5(microtime());
$buid = $userInfo['id'];
$user = mysql_query("SELECT * FROM `scgfx_user_accounts` WHERE `fbid`='".$buid."'");
if(mysql_num_rows($user)>0) {
$userdata = mysql_fetch_assoc($user);
if($userdata['last_request_time']<=(time()-10800)) {
mysql_query("INSERT INTO `scgfx_chats` VALUES('','Welcome back to ".GLOBAL_NAME." <b>".$userdata['fbname']."</b>','0','global','".time()."')");
}
mysql_query("UPDATE `scgfx_user_accounts` SET
`gender` = '".$userInfo['gender']."',
`ses_id` = '".$_SESSION['ses_id']."',
`active` = '1',
`sign_time` = CURRENT_TIMESTAMP,
`last_request_time` = '".time()."',
`ip_address` = '".$_SERVER['REMOTE_ADDR']."' WHERE `fbid`='".$userInfo['id']."'");
} else {
mysql_query("INSERT INTO `scgfx_user_accounts` VALUES('',
'".$userInfo['id']."',
'".$userInfo['name']."',
'".$userInfo['gender']."',
'0',
'".$_SESSION['ses_id']."',
'1',
CURRENT_TIMESTAMP,
'".time()."',
'".$_SERVER['REMOTE_ADDR']."','0','0')");
mysql_query("INSERT INTO `scgfx_chats` VALUES('','We have a new member :) Welcome to ".GLOBAL_NAME." <b>".$userInfo['name']."</b>!<br/>Enjoy your stay!','0','global','".time()."')");
}
if(isset($_SESSION['ses_id'])) {
$getUserInfo = mysql_query("SELECT * FROM `scgfx_user_accounts` WHERE `ses_id`='".$_SESSION['ses_id']."'");
if(mysql_num_rows($getUserInfo)>0) {
while($data=mysql_fetch_assoc($getUserInfo)) {
$_SESSION['fbid'] = $data['fbid'];
$_SESSION['name'] = $data['fbname'];
$_SESSION['gender'] = $data['gender'];
$_SESSION['acctype'] = $data['acctype'];
$_SESSION['points'] = $data['points'];
}
} else {
die("Invalid Session ID");
}
?>
<script>
window.close();
window.opener.location.reload();
</script>
<?php
}
}
else {
$loginurl = $facebook->getLoginUrl(array(
'scope' => 'email,read_stream,offline_access,publish_stream,user_status,user_photos',
'display'=>'popup'
));
header('Location: '.$loginurl);
}
?>
<!-- after authentication close the popup -->
I think this is the only way I can get this code working.
I would try something like this:
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;
session_start();
FacebookSession::setDefaultApplication('app-id','app-secret');
$helper = new FacebookRedirectLoginHelper('this-same-url');
$session = $helper->getSessionFromRedirect();
if($session){
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
echo 'Token: ' . $session->getToken() . '<br/>';
} else {
// Create here your login button
$loginUrl = $helper->getLoginURL(array('public_profile,'));
echo("Login URL:");
echo($loginUrl);
}
Please note that this is a rough sketch and you should never echo the user token. For a more detailed explanation, please read https://developers.facebook.com/docs/php/gettingstarted/4.0.0
I have a simple question,
I have a login and workspace area.
After the user logs in It shows the username of the logged in user at workplace as what I wanted. Now my problem is when user finish filling form available in his workspace the form is then stored in database also i need the username that is coming from session also get stored to the database.
here is code that is storing username and maintaining session after user reach at workspace after login:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/MainProject/connect/auth.php');
session_start();
?>
The final version of the updated insert file :
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
// session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>
In the logging in process, you must store your username in a session
$_SESSION['username'] = $username;
in the process of saving the form, you can call session_start(); and get the session using
$tobeinserted = $_SESSION['username'];
I believe
Remove comment in session start.
Use this.
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
//$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>
This is easily the most bizarre problem that I've ever run into while using the FB api. Maybe I'm just too much of a n00b with their API, but here goes.
I'm using the login button for my site. Upon click, the user will be presented with a pop up from FB telling them some basic info about my app (basic details, number of active users and permissions that it is requesting)
That's all fine and dandy. If the user accepts the app, the page will be reloaded and their info that is being requested from the app will be inserted into the DB and a session will be created.
session_start();
require_once("model/functions.php");
require_once("controller.php");
require_once("model/facebook_api/src/facebook.php");
$facebook = new Facebook(array(
'appId' => '123456789',
'secret' => '123456789',
'cookie' => true
));
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
if($access_token != "")
{
$user = $facebook->getUser();
if($user != 0)
{
$user_profile = $facebook->api("/".$user);
$fb_id = $user;
$fb_first_name = $user_profile['first_name'];
$fb_last_name = $user_profile['last_name'];
$fb_email = $user_profile['email'];
// The FB user_id and all of their other info is correct. Seriously!!
echo $fb_id."<br />";
print_r($user_profile);
// Query the DB to see if this person's info from FB is in there
$query = "SELECT *
FROM users
WHERE fb_id = :fb_id";
$stmt = $db->prepare($query);
$stmt->execute(array(':fb_id' => $fb_id));
$count = $stmt->rowCount();
if($count == 1)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$_SESSION['id'] = $row['user_id'];
$_SESSION['fb_id'] = $row['fb_id'];
$_SESSION['first'] = $row['first_name'];
$_SESSION['last'] = $row['last_name'];
$_SESSION['email'] = $row['email'];
$_SESSION['photo'] = $row['photo'];
$_SESSION['accuracy'] = $row['accuracy_rate'];
}
} else
{
$img_data = file_get_contents('https://graph.facebook.com/'.$fb_id.'/picture?type=large');
$save_path = 'img/profile_pics/large/';
file_put_contents($save_path.''.$fb_id.'.jpg', $img_data);
$insert = "INSERT INTO
users
(first_name,
last_name,
email,
photo,
fb_id,
accuracy_rate,
date_joined,
date_joined_int)
VALUES
(:first_name,
:last_name,
:email,
:photo,
:fb_id,
:points,
:date_joined,
:date_int)";
$params = array(':first_name' => $fb_first_name,
':last_name' => $fb_last_name,
':email' => $fb_email,
':photo' => $fb_id.'.jpg',
':fb_id' => $fb_id,
':points' => '100',
':date_joined' => date("M j, Y"),
':date_int' => idate('z'));
$stmt = $db->prepare($insert);
$stmt->execute($params)or die('error');
print_r($params);
// Query the DB to see if this person's info from FB is in there
$query = "SELECT *
FROM users
WHERE fb_id = :fb_id";
$stmt = $db->prepare($query);
$stmt->execute(array(':fb_id' => $fb_id));
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$_SESSION['id'] = $row['user_id'];
$_SESSION['fb_id'] = $row['fb_id'];
$_SESSION['first'] = $row['first_name'];
$_SESSION['last'] = $row['last_name'];
$_SESSION['email'] = $row['email'];
$_SESSION['photo'] = $row['photo'];
$_SESSION['accuracy'] = $row['accuracy_rate'];
}
}
} else
{
}
} else
{
}
A row is inserted into the DB each time the page is refreshed. No session is ever created. What's even stranger is that the facebook id that is inserted into the fb_id column in the DB belongs to an account that belongs to a test account that FB uses to test open graph actions that are submitted for approval. I know because after taking a deeper look at the DB, I saw a row in the DB that belonged to an FB open graph actions testers. The ID is "2147483647." That is clearly not the ID that is printed out when I printed out the $user_profile array. Furthermore, after the first time the page is reloaded, an insert query shouldn't even occur because the rowCount returned is set to 1. The insert query is only supposed to be executed if the user is a first time user. Sandbox mode isn't on. I thought might have had something to do with it. But, it didn't.
On an unrelated note, is there a bug with FB's api when it comes to doing
$facebook->api("/me");
That doesn't seem to work.
$facebook->api("/".$user);
seems to work just fine though.
Live example can be found here
Facebook user_id could go beyond the supported Integer length. Discovered this on iPhone SDK for a long ID eg. '10000328862128237'. I suspect that is your problem too as I got the exact same number '2147483647'.