I can't seem to get a facebook connect app that I am building to log the user out (sorry no url as it's still in dev). Each time the user clicks a link with the class "logout" the following JS runs which seems to work and even shows the FB modal stating the user has been logged out.
$(document).ready(function(){
$('.logout').click(function(){
//Kill facebook Session
FB.Connect.logout(function() {
window.location = $('.logout').attr("href");
});
});
});
Upon reaching the callback above, the JS sends the user to the logout page where PHP again forces the removal of a custom session and insures that the FB session was removed. Then the user is sent back to the page they were on when they clicked the "logout" link.
//Remove our site session
Auth::logout();
/* FAIL
//Send user to FB logout page and then back here
$logout_url = $this->fb->get_logout_url( site_url( $return_to ? base64_url_decode($return_to) : '' ) );
// Clear any stored state
$this->fb->clear_cookie_state();
exit(header("Location: ". $logout_url));
*/
//FAIL
//$this->fb->logout( site_url( $return_to ? base64_url_decode($return_to) : '' ) );
//FAIL
//Remove user (is this needed..?)
//$this->fb->set_user(NULL, NULL);
//Remove the FB session cookies (in case the JS didn't)
$this->fb->clear_cookie_state();
// Redirect to privious page
redirect( ( $return_to ? base64_url_decode($return_to) : '') );
However, this whole process results in the user being right back where they were and still logged in. A second click on the link seems to do the trick and remove the session though. I have monitored firebug (w/firecookie) and the PHP logout page reports deleting the FB session cookies - yet the next page loaded seems to still use them?!
If anyone knows how to completely DESTROY ALL FACEBOOKS ahem... sessions then please speak up.
:EDIT:
I have even tried to manually remove all cookies on the logout page and it still fails
if( $_COOKIE ) {
foreach( $_COOKIE as $name => $value ) {
//Get the current cookie config
$params = session_get_cookie_params();
// Delete the cookie from globals
unset($_COOKIE[$name]);
//Delete the cookie on the user_agent
setcookie($name, '', time()-43200, $params['path'], '', $params['secure']);
}
}
My guess is that because you are starting the Facebook api classes it reads the session and sets all the cookies again your Javascript call just cleared.
The php facebook lib and the FB js lib both use the same cookienames.
(so you can login through javascript and the php lib will be logged in as well).
There is a specific function for a log out and going to a URL by the way:
FB.Connect.LogoutAndRedirect(url);
Just use the <fb:login-button> tag and make sure you have autologoutlink='true'
Then, when the user is logged in, print out the <fb:login-button> tag and it will show up as a "Logout?" button
Hope that helps.
EDIT:
The docos for login-button: http://wiki.developers.facebook.com/index.php/Fb:login-button
This worked for me (where the redirect page clears the server stuff)
FB.logout(function(response) {
window.location.href="/login/signout";
});
Related
I have visited this link but cant get any help
$facebook->getUser() ALWAYS Returning ID - Can't Logout
the problem is when $facebook->getLogoutUrl is executed it just logout the user from facebook means destroy the facebook session but data return by the app is still there on the page. how to clear that data.
what i want is when logout link is clicked than the data on my app page also clear and login with facebook link appears.
here is the link to my example page
http://www.webdesigncc.info/demoz/myfacebook/examples/example.php
This may solve your problem
function facebook_logout()
{
$logout = $facebook->getLogoutUrl(array('next'=>'your url to be redirected after logout'));
$facebook->destroySession(); /*To destroy facebook sessions.
Available in facebook php sdk*/
$session_destroy(); //Optional if you want to destroy your site's sessions
header("Location:$logout");
}
Using the following way you can clear all datas.
public function destroySession() {
$this->setAccessToken(null);
$this->user = 0;
$this->clearAllPersistentData();
}
I am trying to authenticate (login) a user into facebook while requesting some permissions inside an iframe app.
I am using the JS SDK in conjunction with the PHP SDK. So, first I check if the user is logged in and everything is ok using PHP $facebook->getUser(), when that fails I redirect the user to a page where this JS is run:
FB.getLoginStatus(function(response) {
if (response.status === "connected") {
// Ok, go home
} else {
FB.login(function(response) {
if (response.authResponse) {
// Ok, go home
} else {
// Cancelled, go home
}
}, {scope: '<?php echo implode(',', $this->permissions); ?>'});
}
});
This would then create a login dialog asking for permissions. As you can see there are cases for when the user has authenticated/authorized properly and for when the dialog was canceled. In any of those cases I need to do a single thing: redirect back to the root of my application.
So, the dialog pops, the user logs in and then he is redirected back home, where I use PHP to getUser().
The problem here is that, the first time the user is logged in and redirected, getUser() is always empty, there is no user session. If I refresh the facebook page holding my app's iframe, then there is session and permissions are properly set, indicating that the dialog has done it's job.
Any ideas of why would the first redirect not work?
I found similar issues, but non gives me a specific, working solution.
If anyone else has the same issue, here's what I've learned:
Facebook claims to supply the session cookie to PHP after it's set with JS, but this is NOT true, at least not at all times!
The only solution to this (at least the only one I could think of) is to manually pass the access token whenever you login with JS to your backend (PHP). Store it in a session there, and whenever avaialable use it instead of the access token the Facebook API is trying to use. Just call $api->setAccessToken($yourNewToken);
You can keep on testing to see when exactly will the token be available, but for me it is usually available right after the second api call.
So for some reason, I tried http_referer and it isn't working for me...or maybe it is but this is the reason why I'm trying a workaround. I'm testing a login script in my browser and I want the user to go back to the previous page which they were visiting.
The issue I ran into is when I put in my login credentials, Firefox and Chrome pop out a "Save Password" option and I THINK it acts like a page. So when http_referer is called or when
echo '<script type="text/javascript">javascript:history.go(-1);</script>';
The page is still on the login page! Well what if the user clicks once "Don't Save" and that option is saved...then using history.go(-2) wouldn't work. Here's the workaround I tried but I can't get it to work.
Initially if the login info is correct, I call the first history.go(-1). Then I'm using this function to get the current page and if it matches login.php, I want to go back one more page! But it's not working. Please advise me
if($login_check > 0){
echo '<script type="text/javascript">javascript:history.go(-1);</script>';
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$curpage = curPageName();
if ($curpage = "login.php"){
echo '<script type="text/javascript">javascript:history.go(-1);</script>';
}
}
I've also read to use sessions but my session array saves data for the shopping cart so I'm not sure how I would use sessions for navigation.
Why not store the URL of the page that redirects to the login page in a session and then redirect to it on a successful login? That way even if the user has a few failed login attempts they'll still get to the right page.
Another benefit for this method over javascript is that the redirect is sent in the header on page request, no need to send the user js.
Save the URL as a session variable when the user is not logged in.
// not logged in
$_SESSION['redirect_url'] = 'http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
//now redirect to login page, something like
header("Location: http://www.site.com/login");
Nb. The URL above is crudely constructed, if you are using SSL or a different port (not 80) you'll need to change it accordingly.
Retrieve it on successful login
//login successful
header("Location: ".$_SESSION['redirect_url']);
exit;
I am working on creating a website from scratch and am currently stuck with session stuff.. I know generally how sessions work and how to store things into $_SESSION after session_start() but my main problem is this. After clearing the cache and opening a new window, submitting a login request the FIRST time wont submit correctly and the page reloads and nothing has changed, but AFTER the first time, it works fine...
my login.php handles either a) the post request, or b) the login via url (for testing purposes) so a link to "user/login.php?username=facebook&method=get" would be sent to the code below and set the user to logged in with the name facebook..
<?php
session_start();
$method = $_GET['method'];
if($method == "get") $_SESSION['username'] = $_GET['username'];
else $_SESSION['username'] = $_POST['username'];
header('Location: http://www.imggroups.com');
?>
Im not sure if this matters, but, on the index page, I check to see if the user is logged in by doing this. starting session obviously, then doing. if(isset($_SESSION['username'])) echo whatever i need for logged in.. else echo whatever for not logged in.....
The issue is that you are redirecting the user to a new page, but the old page has not finished closing, so the session is not yet saved.
In order to fix this I usually setup an interum page which redirects to the correct page.
Alternatively you might be able to use session_write_close() (http://www.php.net/manual/en/function.session-write-close.php) before using the header redirect
The fact of the matter is, it is setting the session, BUT it's redirecting you to a different domain that the session isn't allowed on. If you access the website without the 'www.' in front then get redirected to the www version afterwards, then it's going to say your session doesn't exist. Use the following:
session_set_cookie_params(0, '/', ".imggroups.com");
Put it before your session_start() and it will work for both www and non-www versions of your site.
If that is the total of the login.php, I believe there is easier ways to do that:
If it does not matter whether the username actually comes in via _GET or _POST, then use _REQUEST as it encapsulates both.
if( isset($_POST['username'] ) {
$_SESSION['username'] = $_REQUEST['username'];
}
If it does matter, you don't have to trust or use an external parameter, just look at what's there:
if( isset($_POST['username'] ) {
$_SESSION['username'] = $_POST['username'];
} else if( isset($_GET['username'] ) {
$_SESSION['username'] = $_GET['username'];
} else {
// whinge
}
I've not run into that issue with PHP before, but you can also do a session_write_close(); to force it to write out the session before it redirects to the other page.
I also had this same issue if i open new window after logout in new tab or browser and try to log in login page stuck at loading i can see that session has been started because if i refresh on same stuck window i logged in to my dashboard.
But it was resolved later by redirecting it right:
Before
login.php (after ajax successful) --> index.php (if logged in) --> dashboard.php
After
login.php (after ajax successful) --> dashboard.php
hope it saves anybody's time & effort because i suffered alot!
I am doing a web-application using PHP for job searching.
I have one query; when user is not logged in and wants to apply for the job given by clicking 'apply' button, he redirects to the login page. If the user is logged in when clicking, he should get directly to the application page. I'm not sure how to implement this.
I'm confused because I'm new to PHP.
Your question is very vague - maybe start with Authentication in PHP
Well, when the user clicks on 'apply' in your application the user is redirected to the login page if he is not logged in(which you can check if user session exists or not), remember when you redirect the page send the url of the current page in parameters to your login page so that when the user logs in he can be redirected back to the previous page and click on apply for that particular job.....
This is how the logic works, if you want the php, mysql explanation it would take some time for you to understand as you yourself conceded you are new to php..
You could store a value in the Session called "Login" and set this when the user logs in. This can also be used to re-direct the user if they haven't been logged in:
<?php
// check that the session variable does exist
// check that the user 'LoggedIn' has been set to 1 (true)
if (!isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] != 1)
{
// redirect to login page for user to authenticate themselves.
// pass page location (with parameters if necessary) to redirect
// the user on successful login.
header("Location: Login.php?redir=ApplyForJob.php?JobID=12345");
}
else
{
// user is logged in
// redirect the user directly to the apply for job page.
header("Location: ApplyForJob.php?JobID=12345");
}
?>
Can you, when the user logs in, assigns a $_Session variable to that user? i.e., after authentication, you set the $_SESSION['user'] variable.
$_SESSION['user']='admin';
So if you want to check whether the user is already log in after that, just use this:
if(isset($_SESSION['user']))
{
// user is login, direct to the job page
}
else
{
// no login, go to the login page
}
On each page set a cookie or session to which page they were just on:
$expire=time()+60*60*24*30;
setcookie("wherewasi","",time() - 1000);
setcookie("wherewasi",$_SERVER['REQUEST_URI'], $expire);
Then after login redirect them:
$loc = ($_COOKIE['wherewasi'])?$_COOKIE['wherewasi']:'index.php';
header("location: ".$loc);
exit();
There are two things that you need to worry about... checking that they've logged in, and then once they've logged in, directing them to the correct page.
This is all about 'saving state' across page requests. To do this you need can use cookies or more usefully sessions (which may be done via cookies or handled by the PHP engine for you automatically).
Sessions are probably a good way to go. To use sessions, every page needs to start with a
<?php session_start(); ?>
at the very least, before any html code that writes to the browser.
Once that's done you can use your the session variable to store
<?php $_SESSION['user']='joe_blow'; ?>
(and check)
<?php
if(isset($_SESSION['user']) && $_SESSION['user']!='' {
// do something
}
?>
whether the user is logged in, and which page they need to be redirected to after login.
<?php header("location: ".$_SESSION['redirect_location']));
But in order to write the any more useful code I think people would need to know what authentication method you were using... (How are you doing your login? Are you storing ID's in a database? Are you using an off-the-shelf package?)