Take the 2-minute tour ×

I've read loads of threads on this but there is either no answer or the answer given doesn't work for me, so can someone help me spot what's wrong here?

I have the following code to ask the to authorize my facebook app if they haven't already authorized it. Once authorized, it should redirect to the same page but this time it shouldn't need to ask for authorization.

The code asks for user authorization perfectly...works exactly as I want, but when the app reloads $user is always set to 0.

Here's my code:

require_once 'facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
    'appId' => 'xxxxxxxxxxxxxxx',
    'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'cookie' => true
    // Get User ID
    $user = $facebook->getUser();

    if ($user) {
        try {
            echo "logged in and authenticated";
        } catch (FacebookApiException $e) {
            $user = null;

    // Ask for authorisation
    if(!$user) {
        $login_url = $facebook->getLoginUrl(
                'canvas' => 1,
                'fbconnect' => 0,
                'scope' => 'email,publish_stream',
                'redirect_uri' => 'myurl - same as Site URL in app basic settings'
        echo "<script> top.location.href='" . $login_url . "'</script>";


After the user has authorized the app, it doesn't ask for authorization again so I'm assuming the authorization worked, but why is $facebook->getUser() returning 0?

The URL after the redirect has 2 querystring parameters - 'state' and 'code'. Are they relevant? Should I be doing something with them? As far as I know I've downloaded the latest facebook SDK so I'm at a loss on how to get this working.

Please help!!

I forgot to mention....I'm calling the above code via ajax

share|improve this question
add comment

1 Answer

OK, I've sorted this. The code does work, it's just the fact I'm running via ajax that's the problem. Once I used it as a proper page load rather than an ajax call it all works :)

share|improve this answer
add comment

Your Answer


