Access Facebook Session using PHP

2019-05-11 11:59发布

问题:

I am struggling to keep the Facebook session alive using PHP on my website.

I use both the JavaScript SDK and the PHP SDK to form the basis of my app.

The problem I am having is that when the "Facebook session" ends, my PHP script believes that you are logged out of Facebook. But, as soon as I call the FB.init() using the JavaScript SDK, the session comes back to life.

Is there anyway to achieve the same using the PHP SDK? Or can I set a custom expiry time on the Facebook session?

Extracted from comments

It seems that the session expire time is set to 2 hours but I am not certain about this. I don't think calling the PHP api will make a difference. I need to explain a little clearer what is happening. Basically, if you arrive at my home page, you get the option to login via Facebook. If you do, this all works fine! Once you are logged in and you have authorized the app, this is okay until the session expires. When the session expires, it seems that the PHP SDK is unable to determine whether or not you are logged in via Facebook, however, the Javascript SDK is. I use getUser() for the PHP SDK.

In other words, because the session has expired, PHP thinks that you are no longer logged in via Facebook. The Javascript SDK is able to detect whether or not you are logged in, regardless of whether the session is there. When it realises you are, it recreates the session any way. But in order for the session to be picked up by PHP, the page obviously needs to be refreshed. This is the problem I have, because the page displays content based on your Facebook login, I need the PHP SDK to be able to recreate the session as well, so that it is not necessary to refresh the page.

回答1:

Ok... Not to sure what the exact details of why your session are acting like this - I must state too that I am not very well versed in PHP sessions and have not has extensive experience with them.

My suggestion would be to let the JavaScript SDK do its work... let it "re-detect" your session successfully and after it has done so, make an AJAX call to your server. In the processing of that call you can create and re-initiate the PHP SDK hence reviving your session.

Additionally you could call the FB.getAuthResponse periodically to ensure that the users session is still valid ( at least in the JavaScript SDK ).

From the Fb.getLoginStatus() documentation :

{
    status: 'connected',
    authResponse: {
        accessToken: '...',
        expiresIn:'...',
        signedRequest:'...',
        userID:'...'
} }

By testing for the presence of the authResponse object within the response object, you can be sure the user is known to your app and you can begin to make further calls to the Facebook APIs. If the authResponse object is not present, the user is either not logged into Facebook, or has not authorized your app.