Dustin
Dustin

Reputation: 4459

$facebook->getUser(); STILL returning 0

I see this has been asked a lot here but I still have yet to come up with a solution. I need to get the user's ID to determine if they have already filled out a form in my app. Here is my code..

require_once('facebook.php');  
$facebook = new Facebook(array(  
'appId'  => 'xxxxxxxxxx',  
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',  
'cookie' => false,  
)); 

$signed_request = $facebook->getSignedRequest();
$page_id = "fb" . $signed_request['page']['id'];
$user_id = $facebook->getUser(); 

I don't know if this is related or not but I can grab the page id just fine. But $user_id keeps returning as 0 for all users except me. I'm guessing that's because I'm an admin of my page.

Does anybody know what the problem is here?

Upvotes: 2

Views: 997

Answers (2)

danielv
danielv

Reputation: 3097

My guess is that most of the reported problems with $facebook->getUser() are related to CSRF (Cross Site Request Forgery) protection that is built into Facebook's PHP SDK and is implemented somewhat awkwardly.

What CSRF protection does is to make sure that a request to get user's data needs to originate from the same server. It does it by storing a random hash in the session. If you call to getUser() without this value set, getUser() will always return 0.

So the user needs to visit your site first, a CSRF token will be generated and stored in the session and only on the following requests you can successfully call getUser()

If you look at the PHP SDK source code you'll notice that the way to generate this CSRF token is to call a protected method called establishCSRFTokenState(). You can't call this method from outside and the only way it gets called is when calling $facebook->getLoginUrl(...)

So, either modify the SDK source to change this behavior (or to make establishCSRFTokenState() public) or just call getLoginUrl(...) when the user first visits your site. Make sure that you have session support enabled.

I think this isn't designed very well and documented even worse. And it doesn't help to protect the site against CSRF attacks in most cases unless people understand how to properly use it.

Upvotes: 2

Andreas
Andreas

Reputation: 1617

i has this problem too, the only solution was to use oauth before with permission request "user_about_me". Since FB uses oauth 2.0, most user values are hidden and you have to request all this sh*t :(

Upvotes: 0

Related Questions