PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, March 6, 2022

[FIXED] Getting facebook current session details like user_id in different pages

 March 06, 2022     ajax, facebook, facebook-javascript-sdk, facebook-php-sdk, session-variables     No comments   

Issue

My main page is index.php. Here I perform user login and then redirected to url.php using ajax request. Now user may move to various pages.

I need current user facebook id on those pages. How can I get it?

login.php

 <script type="text/javascript">
    window.fbAsyncInit = function() {
      FB.init({
        appId: '<?php
        echo $appId;
        ?>',
        cookie: true,
        xfbml: true,
        //  channelUrl: '<?php
        echo $return_url;
        ?>channel.php',
        oauth: true}
             );
    };
    (function() {
      //alert("1");
      var e = document.createElement('script');
      e.async = true;
      e.src = document.location.protocol +'//connect.facebook.net/en_US/all.js';
      document.getElementById('fb-root').appendChild(e);
    }());
    function CallAfterLogin(data,callback){
      FB.login(function(response) {
        if (response.status === "connected")
        {
          LodingAnimate();

          FB.api('/me?fields=movies,email,name', function(mydata) {

              $.post('movies_db.php',{'myd':a, name: name, email: email, myid:myid}, function(data) 
                     {
                       $.ajax({
                         url:'url.php'
                         ,async:     true
                         ,type : 'POST'
                         ,cache:     false
                         ,data : 'myid=' + myid
                         ,dataType:  'html'
                         ,success:   function(data){
                           $('body').html(data);
                           FB.XFBML.parse();
                         }
                       }

I tried in this way: on url.php/ or whatever page at which I want to get session info

$id= $_SESSION['fb_<appID>_user_id'];
echo "X is $id";

Another try using php sdk:

require_once("facebook.php"); //given correct path

$config = array();
$config['appId'] = '1788xxxxxx2';
$config['secret'] = '390c04c60xxxxxxxxx68aca44';

$facebook = new Facebook($config);

$appId = $facebook->getAppId();  //gives correctly
$uid = $facebook->getUser();   //always 0
echo "$uid";

one more try:

<?php
session_start();
print $_SESSION['fb_<myAppID>'];  //prints correct
//print $_SESSION['fb_<userID>'];
print $_SESSION['fb_<myAppID>_user_id'] = '<user_id>';  //does not print anything
//echo "id :$x";
?>

No luck. Any other idea? Or where is the mistake here?


Solution

UPDATE

JS (jQuery)

script.js

  $('#login').click( function(e){

      e.preventdefault;

        FB.login(function(r) {
        if (r.authResponse) {
            var accessToken = r.authResponse.accessToken;
            $.ajax({ 
                type     : "GET",
                url      : "set-session.php",
                data     : { accessToken : accessToken },
                datatype : 'json',
                success  : function(user) {
                                    $('p').fadeOut( function() { 
                                         $('p').html('Hey, Good to see you <a href='+ user.link +'>'+ user.first_name +'</a>!</p>');
                                         $('p').fadeIn();
                                    });
                                    $('#login').fadeOut().remove();
                           },
                error    : function() {
                                    $('p').fadeOut( function() { 
                                         $('p').html('Something went wrong :( try again');
                                         $('p').fadeIn();
                                    });          
                           }
            });
        } else {
            $('p').fadeOut( function() { 
                 $('p').html('You didn\'t authorize the app');
                 $('p').fadeIn();
            }); 
          }
      });

    });

PHP

set-session.php

<?php
require_once 'facebook-sdk/facebook.php';
header('Content-Type: application/json');

if ( isset($_GET['accessToken']) && !empty($_GET['accessToken']) ) {

        $accessToken = $_GET['accessToken'];
        $facebook    = new Facebook(array(
                                    'appId'  => '1419692231579671',
                                    'secret' => 'd69245290e6c6fb1346faa32437652c5',
                                    'cookie' => true
        ));

        # set the access_token for $facebook for future calls
        $facebook->setAccessToken($accessToken);

        try {

             $userData = $facebook->api('v2.0/me');
             # register a new session for the user, containing their basic information, id, username, first_name, last_name, profile_picture
             # and another one for the access_token.
             $_SESSION['fb-user-token'] = $accessToken;
             $_SESSION['fb-user']       = $userData;

             echo json_encode( array('id'         => $userData['id'],
                                     'link'       => $userData['link'],
                                     'username'   => $userData['uesrname'],
                                     'first_name' => $userData['first_name'],
                                     'last_name'  => $userData['last_name'],
                                     'gender'     => $userData['gender']      ), JSON_PRETTY_PRINT);

        } catch (FacebookApiException $e) {

           error_log($e);

        }

} else {
   header('HTTP/1.1 400');
}

Index

index.php

<?php
if ( isset($_SESSION['fb-user']) ) {
    $user = $_SESSION['fb-user'];
?>
    <div>
       <p>Hey, Good to see you <a href="<?php echo $user['link'] ?>"><?php echo $user['first_name']; ?></a>!</p>
    </div> 
<?php
    } else {
?>
    <div>
       <p>Hey there, Login with your Facebook</p>
    </div>
    <a class="fsl fsl-facebook" href="#" id="login">
       <span class="fa-facebook fa-icons fa-lg"></span>
       <span class="sc-label">Login W/ Facebook</span>
    </a>    

<?php  
}
?>

DEMO

You can download & contribute to this repository on GitHub



Answered By - Adam Azad
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing