Both examples should leave the user logged in. The necessary login data is stored in a cookie and re-used.
What might be the problem: I have found that the "$user = $facebook->getUser();" call sometimes fails even through the user is logged in. My advice is not to rely on that call, but skip to the try/catch block below, and set the user from there.
try {
$user_profile = $facebook->api('/me');
$user = $user_profile['user_id'];
} catch (FacebookApiException $e) {
$user_profile = false;
$user = null;
}
As this appears more reliable.
Failing that, you can control it all yourself. Steps are:
- Tell Javascript not to use cookies
- Log the user in and use the "getAccessToken" function to get the access token of a logged in user. Store that in a cookie of your own name/duration.
- Next time a page loads, check for the access token cookie you created, and use "setAccessToken" and then folow the same try/catch block. If the user return invalid, then clear your own cookie as that means the accesstoken has been invalidated by the user.
You shouldn't need this last approach (unless sharing tokens between sessions/devices, or desiring offline access) as that's exactly what the facebook SDK does - but it does help you control and understand hte process more.
Finally, you can do all of the login / getAccessToken / store cookie method though JavaScript, thus logging the user in and remembering it without refreshing the page. Just check the appropriate action on auth.login to remember the cookie and change page contents - don;t reload the page.
The cookie will be read by PHP next time the user refreshes the page / returns to the site. Remember to clear the cookie on logout.
So you can do what you want, yes.