Search code examples
phpcodeigniterfacebook-graph-apifacebook-php-sdkaccess-token

How to bypass facebook PHP login method if you already have a valid auth_token


I'm using this library for Facebook graph API access within my codeigniter project: http://www.haughin.com/code/facebook/

My web app uses the Facebook JS SDK to authenticate users client-side, then immediately after a login is completed the user's user-id and session object are sent to my server via an AJAX request. I want to make a call to the graph API from the server to receive the user's basic information, so I'm wondering if there's a way I can bypass the need to call the facebook->login() method to receive a session via a redirect from facebook? Anyone know how to do this?


Solution

  • I don't recommend the Facebook SDK at all. You have a lot more control if you do things yourself and it becomes a lot simpler. Just set up a cURL function like:

    function curl($url, $request = 'GET'){
        $ch = curl_init();
        $curlopt = array(
            CURLOPT_URL => $url,
            CURLOPT_CUSTOMREQUEST => $request,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 60,
            CURLOPT_USERAGENT      => 'facebook-php-2.0',
        );
        curl_setopt_array($ch, $curlopt);
        $response = curl_exec($ch);
        if($response === false)
            trigger_error(curl_error($ch));
        curl_close($ch);
        return $response;
    }
    

    And then a Facebook api function like:

    function fb_api($url, $access_token = false, $request = 'GET'){
        $url = 'https://graph.facebook.com/'.$url;
        if($access_token)
            $url .= (strstr($url, '?') ? '&' : '?').'access_token='.$access_token;
        return json_decode(curl($url, $request), true);
    }
    

    Then you can make your request to the graph api like:

    fb_api('me', $access_token);