Twitter oAuth Connection issue - php

I am doing Login with twitter in my application and using Twitter oAuth. I am placing proper consumer key and proper consumer secret key and valid callback url still having a error
Could not connect to Twitter. Refresh the page or try again later.
so what should I do now. couldn't trace out what is causing the trouble.
My index file
<?php
/**
* User has successfully authenticated with Twitter. Access tokens saved to session and DB.
*/
/* Load required lib files. */
session_start();
require_once('oauth/twitteroauth.php');
require_once('twitter_class.php');
if(isset($_GET['connect']) && $_GET['connect'] == 'twitter'){
$objTwitterApi = new TwitterLoginAPI;
$return = $objTwitterApi->login_twitter($_GET['connect']);
if($return['error']){
echo $return['error'];
}else{
header('location:'.$return['url']);
exit;
}
}
?>
My callback.php
<?php
session_start();
require_once('oauth/twitteroauth.php');
require_once('twitter_class.php');
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
$_SESSION['oauth_status'] = 'oldtoken';
header('Location: destroy.php');
}else{
$objTwitterApi = new TwitterLoginAPI;
$connection = $objTwitterApi->twitter_callback();
if( $connection == 'connected'){
header('Location: index.php?connected=Y');
exit;
}else{
header('Location: index.php?connected=F');
exit;
}
}
Help me on this hence i am new to this couldn’t trace out the actual problem.
PS: in oAuth there is always a blank response if curl

Related

How to fix The page isn’t redirecting properly

I am trying to login with google api for php and then redirect the user to the dashboard.php but suddenly this error occurred during the redirection
my files:
the callback file that is responsible for tokens and redirection to dashboard.php
<?php
session_start();
require_once("../gog.php");
if (isset($_SESSION['access_token']))
$gClient->setAccessToken($_SESSION['access_token']);
else if (isset($_GET['code'])) {
$token = $gClient->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['access_token'] = $token;
} else {
header('Location:../index.php');
exit();
}
$oAuth = new Google_Service_Oauth2($gClient);
$userData = $oAuth->userinfo_v2_me->get();
header('Location:../client/dashboard.php');
exit();
?>
the gog.php which includes the settings (i deleted the values)
<?php
require_once "vendor/autoload.php";
$gClient = new Google_Client();
$gClient->setClientId("");
$gClient->setClientSecret("");
$gClient->setApplicationName("");
$gClient->setRedirectUri("");
$gClient->addScope("");
$loginURL = $gClient->createAuthUrl();
?>
the index php where it testes wether or not the user is signed in with google account or email pwd
<?php
require_once("includes/config.php");
require_once("gog.php");
require_once("includes/classes/Account.php");
$account=new Account($con);
if(isset($_SESSION["clientLoggedIn"]) || isset($_SESSION['access_token']) ){
header('location:client/dashboard.php');
exit();
}
?>
the config.php file included which has the database setting to connect
<?php
ob_start();
session_start();
try{
$con= new PDO("mysql:dbname=cinecad;host=localhost","root","");
$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
}catch(PDOException $e){
exit("Connexion failed:".$e->getMessage());
}
?>
and the finally the dashbaord.php
<?php
session_start();
if(!isset($_SESSION["clientLoggedIn"])||!isset($_SESSION['access_token'])){
header("Location:../index.php");
}
?>
Based on #Alon Eitan comment the answer was
$_SESSION["clientLoggedIn"] = true

Session variable being destroyed after migrating to live website

I've just migrated my website from my local WAMP server to a live HTTPS server on 1and1. It works perfectly on the local server, but on the live server the session variables are being destroyed when I'm trying to log in. I know the database is working fine and all the queries are running successfully after some testing.
The problem is that the session variable is being created when I run the log in script, but once the page reloads and runs a 'session check', the variable no longer exists. Because of this the site just reloads the login form as the if condition is not being met.
Here is the code for both scripts. I don't know why this is happening as the entire website is being run through HTTPS so its not an issue with HTTP/HTTPS etc.
LOGIN SCRIPT
<?php
date_default_timezone_set("Europe/London");
require("db_connect.php");
if ($sql)
{
$email = $_POST['userEmail'];
$password = $_POST['userPassword'];
$checkDetails = mysqli_query($sql, "SELECT * FROM users WHERE email='$email'");
while ($details = mysqli_fetch_array($checkDetails))
{
$hashedPassword = $details['password'];
if(password_verify($password, $hashedPassword))
{
//Passwords Match
//Update last login time in the database
$now = date("Y-m-d H:i:s");
$lastLoginQuery = mysqli_query($sql, "UPDATE users SET lastLogin='$now' WHERE email='$email'");
if ($lastLoginQuery)
{
//Initialise session
session_start();
$_SESSION['user'] = $email;
header("Location: ../");
}
else
{
echo "There was an error logging you in. Please try again!";
}
}
else
{
echo "The details you entered are incorrect. Please return to the login page. If the problem persists, contact an administrator.";
}
}
}
else
{
echo "There was a problem connecting to the database";
}
?>
SESSION CHECKING SCRIPT
<?php
//Check if a session exists and load the page if it does
session_start();
if (isset($_SESSION['user']))
{
//Check if the session has timed out
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800))
{
//Last user action performed more than 30 minutes ago. Log out now.
session_unset();
session_destroy();
header("Location:./");
}
//If the session hasnt timed out. Reset the last activity time.
$_SESSION['LAST_ACTIVITY'] = time();
//Continue to load content
include('./includes/main.php');
}
else
{
// Load login page
include('./includes/login_form.php');
}
?>
Session start must be the very first call in your script. https://www.w3schools.com/php/php_sessions.asp
<?php
session_start();
date_default_timezone_set("Europe/London");
require("db_connect.php");
etc...
Fixed the issue by adding an additional session_start(); directly at the beginning of the index.php file before any html. Seems strange that the login and session_check scripts wouldn't work without this as they also had session_start(); in them too.

PHP Page isn't storing cookies

I am new to php and I am making a basic login script.
All I want to do is log in and have the cookie for my user_id stored.
It works on all of my other pages, except my index page which is one directory up.
So on my index page, I have this if statement:
<?php
if (!isset($_COOKIE['user_id'])) {
sign_in();
} else {
echo "You're already logged in!";
}
?>
No matter what I do, the sign_(); function always shows.
But here's the kicker:
On my login script, the whole thing goes through as if I successfully logged in.
I send it back to this page using:
header("Location: ../index.php");
(It is up one directory)
However, when I make it link to a page in the same directory, it registers the cookie and everything is alright.
header("Location: show_user.php");
If you want a hands on view, you can go to http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/signup.php to make your account. And http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/show_user.php to view it. And notice how the index page doesn't register the cookie.
How I tried to set the cookie:
if (isset($_POST['usernamelogin'])) {
$user_login = $_REQUEST['usernamelogin'];
$pass_login = $_REQUEST['passwordlogin'];
$pass_login = trim(crypt($pass_login, $user_login));
$login_query = sprintf("SELECT username, user_id FROM user WHERE username = '%s' and password = '%s';", mysql_real_escape_string($user_login), mysql_real_escape_string($pass_login));
$loginresult = mysql_query($login_query, $dbConn);
echo $login_query;
if (mysql_num_rows($loginresult) == 1) {
$userinfo = mysql_fetch_array($loginresult);
$username = $userinfo['username'];
$userid = $userinfo['user_id'];
setcookie('username', $username);
setcookie('user_id', $userid);
header("Location: show_user.php");
exit();
} else {
echo "Couldn't find your account!";
}
}
Please excuse my unrefined page and amateur mistakes. I have a lot to learn.
Any ideas?
Thank you for your time.
Check if you have the cookie with the following
<?php
var_dump($_COOKIE);
//if (!isset($_COOKIE['user_id']))
if (empty($_COOKIE['user_id']))
{
sign_in();
}
else {
echo "You're already logged in!";
}
?>

Store Twitter Tokens in mysql database

I can't seem to save the Twitter user_id, screen_name, oauth_token and oauth_token_secret (from a logged in user) into a mysql database that I've set up?
I'm using the Abraham Williams Oauth library.
That code works fine and I can see the components that make up the access_token by using a print_r request when a user logs in, however the tokens aren't saved into the table 'users' in the database 'tokens'?
I've read nearly all the questions/answers on SO and tested every bit of code however I can't seem to get a simple INSERT to work for these tokens? I've also hard coded some test components into the config_db file (as an INSERT) and they load fine.
Callback code:
<?php
require_once("/path/config_db.php");
session_start();
// Include class & create
require_once('/path/config.php');
require_once('/path/twitteroauth/twitteroauth.php');
// User has selected to DENY access
if(!empty($_GET["denied"])) {
// could re-direct or display cancelled view/template
// we're just echoing out a message
echo "No deal! <a href='index.php'>Try again?</a>";
die();
}
/* 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';
header('Location: ./clearsessions.php');
}
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/* Request access tokens from twitter */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
//echo "RECEIVED TOKENS<br>";
// Check we have valid response
if(is_numeric($access_token["user_id"])) {
// Save the access tokens to a DB (we're using a session)
/* Save the access tokens. Normally these would be saved in a database for future use. */
$_SESSION['access_token'] = $access_token;
//GET CREDENTIALS VIA API
$credentials = $connection->get('account/verify_credentials');
//insert tokens into db
print_r($_SESSION["access_token"]);
$sql="INSERT INTO users (`user_id` ,`screen_name` ,`oauth_token` ,`oauth_token_secret`)
VALUES ('".$_SESSION["access_token"]["user_id"]."',
'".$_SESSION["access_token"]["screen_name"]."',
'".$_SESSION["access_token"]["oauth_token"]."',
'".$_SESSION["access_token"]["oauth_token_secret"]."'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
//echo $query;
//echo mysql_error();
print_r($_SESSION["access_token"]);
$message = array('status' => 'Test OAuth update. #testoauth');
$test = $connection->post('statuses/update', array('status' => 'Just a test '));
/* 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';
header('Location: ./callback.php');
} else {
/* Save HTTP status for error dialog on connnect page.*/
header('Location: ./clearsessions.php');
}
?>
<? print_r($access_token); ?>
The connection (config_db file) is as follows
<?php
$con=mysqli_connect("server","username","password","tokens");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
The table 'users' is as follows:
$sql = "CREATE TABLE users
(
user_id INT(11),
screen_name varchar(50),
oauth_token varchar(90),
oauth_token_secret varchar(90),
)";
You have a syntax error on sql query. you forget the close parentheses.
'".$_SESSION["access_token"]["oauth_token_secret"]."'"; change this
'".$_SESSION["access_token"]["oauth_token_secret"]."')";

PHP sdk - redirection error

I have a website in which I have the following files :-
index.php - homepage
f-login.php - page which redirects user to facebook to ask for permissions
add.php - which is given below - this page checks if the user is old or new. If the user is new, it redirects the page to username-choice.php or else it redirects the user to the main page after setting the required cookies.
username-choice.php - This page is for the NEW user to choose a username for himself. If the cookie - "tempuid" is set, it shows the correct page or else it shows an error page that "COOKIES ARE NOT ENABLED!"
The problem is that in the username-choice.php page the error message shows up. I cannot understand the problem. I have given my code for the add.php page. Please tell me what's wrong. Any help shall be appreciated.
The following is my add.php page :-
<?php
include "config.php"; /* contains mysqli_connect */
require "src/facebook.php"; /* for facebook login php-sdk */
include "app_details.php"; /* app-id and secret */
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);/* ERROR TO BE DISPLAYED */
$user = null;
}
}
$uid=$user_profile['id'];
$email=$user_profile['email'];
$fullname = $user_profile['name'];
$birthday = $user_profile['birthday'];
if($uid==null){
echo "Sanp! Something went wrong";
}
$n=0;
$result = mysqli_query($con,"SELECT * FROM Users
WHERE UID='$uid'");
/* TO CHECK IF THE USER IS NEW OR OLD*/
while($row = mysqli_fetch_array($result))
{
$n++;
$username=$row['Username'];
$ppic=$row['Ppic_url'];
}
if($n>0)
{
$expire=time()+60*60*24*30;
setcookie("name" , "$fullname", $expire);
setcookie("uid" , "$uid", $expire);
setcookie("logintype", "facebook", $expire);
setcookie("username", "$username", $expire);
setcookie("ppic", "$ppic", $expire);
header("Location: http://mysite.com");
exit;
}
else if($n==0)
{
$expire=time()+60*60*24*30*365;
setcookie("tempname", "$fullname", $expire);
setcookie("tempuid" , "$uid", $expire);
setcookie("tempemail", "$email", $expire);
setcookie("tempbday", "$birthday", $expire);
setcookie("tempppic", "$ppic", $expire);
header("Location: http://mysite.com/username-choice");
exit();
mysqli_close($con);
}
?>
This means that the program is going into the last if statement. Now, your webpage can display "COOKIES NOT ENABLED" only if the uid is null. So, according to me the $uid is null.

Categories