Facebook Api - saving profile image - php

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'];
}
}

Related

Facebook login error in codeigniter?

Controller:
public function login()
{
$userData = array();
if($this->facebook->is_authenticated())
{
$userProfile = $this->facebook->request('get', '/me?fields=id,first_name,last_name,email');
$userData['oauth_provider'] = 'facebook';
$userData['oauth_uid'] = $userProfile['id'];
$userData['firstname'] = $userProfile['first_name'];
$userData['lastname'] = $userProfile['last_name'];
$userData['email'] = $userProfile['email'];
$userData['password'] = rand();
$userID = $this->user->checkUser($userData);
if(!empty($userID))
{
$data['userData'] = $userData;
$this->session->set_userdata('userData',$userData);
}
else
{
$data['userData'] = array();
}
$data['logoutUrl'] = $this->facebook->logout_url();
}
else
{
$fbuser = '';
$data['authUrl'] = $this->facebook->login_url();
}
if($this->session->userdata('loggedIn') == true)
{
redirect('test/profile');
}
if(isset($_GET['code']))
{
$this->google->getAuthenticate();
$gpInfo = $this->google->getUserInfo();
$userData['oauth_provider'] = 'google';
$userData['oauth_uid'] = $gpInfo['id'];
$userData['firstname'] = $gpInfo['given_name'];
$userData['lastname'] = $gpInfo['family_name'];
$userData['email'] = $gpInfo['email'];
$userData['password'] = rand();
$userID = $this->user->checkUser($userData);
$this->session->set_userdata('loggedIn', true);
$this->session->set_userdata('userData', $userData);
redirect('test/profile');
}
$data['loginURL'] = $this->google->loginURL();
$data['student_id'] = $this->session->userdata('student_id');
$this->load->view('header-inside',$data);
$this->load->view('login',$data);
}
In this code I have create facebook login and google login on same page i.e. login.php where google login work perfectly and facebook login also working but it gives some error like when I have login with facebook. It will show some error like:
Type: Google_AuthException
Message: Error fetching OAuth2 access token, message: 'invalid_grant'
I don't know why. So, How can I fix this problem ? Please help me.
Thank you
separate the logic of google authentication and Facebook authentication , this variable get set when you try to authenticate with Facebook $_GET['code'] due to which it entre the the google authentication code and it gives the error Message: Error fetching OAuth2 access token, message: 'invalid_grant'

Android JSON error (via PHP API) after MySQL foreign key relationship

I have an android app that sends data to a MySQL PHPMyAdmin table. The data stores in the database perfectly. I have two tables named event and activity. So I created a foreign key in activity that relates to the eid field in event. It shows the relation properly in the Designer section in PHPMyAdmin too. But the problem is, now I get a JSON error from the android application. I can't seem to figure out why. I added the code db.execSQL("PRAGMA foreign_keys=ON;"); in the onCreate method of the DBHelper class too. The error I get is the json_encode error response. Here's my php code for reference:
if ($tag == 'newAct'){
$aName = $_POST['aname'];
$aType = $_POST['atype'];
$aDesc = $_POST['adesc'];
$aSdate = $_POST['asdate'];
$aEdate = $_POST['aedate'];
$aStime = $_POST['astime'];
$aEtime = $_POST['aetime'];
$aGoal = $_POST['agoal'];
$aLocation = $_POST['alocation'];
$aCreated_by = $_POST['acreated_by'];
//$subject = "New activity";
//$message = "You have sucessfully created a new activity.\n\nRegards,\nAdmin.";
//$from = "Shareity Team";
//$headers = "From:" . $from;
$activity = $db->addActivity($aName, $aType, $aDesc, $aSdate, $aEdate, $aStime, $aEtime, $aGoal, $aLocation, $aCreated_by);
if ($activity) {
// activity stored successfully
$response["success"] = 1;
$response["activity"]["aname"] = $activity["aname"];
$response["activity"]["atype"] = $activity["atype"];
$response["activity"]["adesc"] = $activity["adesc"];
$response["activity"]["asdate"] = $activity["asdate"];
$response["activity"]["aedate"] = $activity["aedate"];
$response["activity"]["astime"] = $activity["astime"];
$response["activity"]["aetime"] = $activity["aetime"];
$response["activity"]["agoal"] = $activity["agoal"];
$response["activity"]["alocation"] = $activity["alocation"];
$response["activity"]["acreated_at"] = $activity["acreated_at"];
$response["activity"]["aedited_at"] = $activity["aedited_at"];
$response["activity"]["acreated_by"] = $activity["acreated_by"];
//mail($email,$subject,$message,$headers);
echo json_encode($response);
}
else {
// activity failed to store
$response["error"] = 1;
$response["error_msg"] = "JSON Error occured in creating the activity WTF";
echo json_encode($response);
}
This is the addActivity function
public function addActivity($aname, $atype, $adesc, $asdate, $aedate, $astime, $aetime, $agoal, $alocation, $acreated_by) {
$uuid = uniqid('', true);
//$hash = $this->hashSSHA($password);
//$encrypted_password = $hash["encrypted"]; // encrypted password
//$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO activity(aname, atype, adesc, asdate, aedate, astime, aetime, agoal, alocation, acreated_at, aedited_at, acreated_by) VALUES('$aname', '$atype','$adesc', '$asdate', '$aedate', '$astime', '$aetime', '$agoal', '$alocation', NOW(), NOW(),'$acreated_by')");
// check for successful store
if ($result) {
//get event details
$activityid = mysql_insert_id(); // last inserted id
//$eventid = mysql_insert_id();
$result = mysql_query("SELECT * FROM activity WHERE activityid = $activityid");
//return event details
return mysql_fetch_array($result);
} else {
return false;
}
}

how to get detail of all follower of twitter(not followers count) in php?

Here is code which works fine to get count of followers and following .but i want to show every follower all details (pic,username,id etc)..actually i did this for instagram by using method $followingdata = json_decode($instgram->getFollowing(20));
what i do for twitter.
<?php
require('http.php');
require('oauth_client.php');
$client = new oauth_client_class;
$client->debug = 1;
$client->server = 'Twitter';
$client->redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].
dirname(strtok($_SERVER['REQUEST_URI'],'?')).'/login_with_twitter.php';
$client->client_id = 'my client id'; $application_line = __LINE__;
$client->client_secret = 'my client secret';
if(strlen($client->client_id) == 0
|| strlen($client->client_secret) == 0)
die('Please go to Twitter Apps page https://dev.twitter.com/apps/new , '.
'create an application, and in the line '.$application_line.
' set the client_id to Consumer key and client_secret ... '.
'The Callback URL must be '.$client->redirect_uri);
if(($success = $client->Initialize()))
{
if(($success = $client->Process()))
{
if(strlen($client->access_token))
{
$success = $client->CallAPI(
'https://api.twitter.com/1.1/account/verify_credentials.json',
'GET', array(), array('FailOnAccessError'=>true), $user);
}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if($success)
{
$following =$user->friends_count;
$followers =$user->followers_count;
?>
You could try something like:
using (WebClient client = new WebClient())
{
string url = "http://twitter.com/users/show.xml?screen_name=[username]";
string response = client.DownloadString(url);
}
Regards

Webrequest from Android returns different content as on PC

hy!
I call my webservice from android:
HttpConnection con = new HttpConnection("XXX/login", handler);
con.setParameter("username",user.getText().toString());
con.setParameter("password",new MD5(pw.getText().toString()).getMD5());
con.start();
Log:
10-12 14:35:52.123: ERROR/NFF User(265): test
10-12 14:35:52.123: ERROR/NFF PW(265): 098f6bcd4621d373cade4e832627b4f6
10-12 14:35:53.443: ERROR/NFF(265): { what=0 when=3917056 obj={"Data":null,"Details":"not authorized","Status":403}
10-12 14:35:53.443: ERROR/NFF(265): }
On Pc (login?user=test&password=098f6bcd4621d373cade4e832627b4f6):
{"Data":null,"Details":"bad request","Status":400}
Php:
<?php
if (!isset($_REQUEST['username']) || !isset($_REQUEST['password']))
{
die(json_encode(array("Data"=>null, "Details"=>"bad request", "Status"=>400)));
}
include "db_connect.php";
$response = array("Data"=>null, "Details"=>null, "Status"=>null);
$result = mysql_query("SELECT * FROM USER WHERE USER_NAME = '".mysql_real_escape_string($_REQUEST['username'])."' AND PASSWORD = '".mysql_real_escape_string($_REQUEST['password'])."'");
$line = mysql_fetch_assoc($result);
if ($line != null)
{
session_destroy();
session_start();
mysql_query("UPDATE USER SET USER_SESSION = '".mysql_real_escape_string(session_id())."' WHERE USER_ID = '".mysql_real_escape_string($line['USER_ID'])."'");
$_SESSION['authenticated'] = true;
$_SESSION['USER_ID'] = $line['USER_ID'];
$response['Status'] = 200;
$response['Data']['session_id'] = session_id();
}
else
{
$response['Status'] = 403;
$response['Details'] = "not authorized";
}
echo json_encode($response);
?>​
Why are the words "what=0 when=3917056" from the android request included?
Please help
I think what and when belong to the android message that is sent to a handler
http://developer.android.com/reference/android/os/Message.html#what
and are logged as you log the whole message.
The structure looks something like this
Message{
what=0
when=3917056
obj=(This is your actual result)
}
So no worries ;-)

Can somebody help me with posting a status on twitter?

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.

Categories