How to log out user from web site using BASIC authentication?











up vote
233
down vote

favorite
105












Is it possible to log out user from a web site if he is using basic authentication?



Killing session is not enough, since, once user is authenticated, each request contains login info, so user is automatically logged in next time he/she access the site using the same credentials.



The only solution so far is to close browser, but that's not acceptable from the usability standpoint.










share|improve this question




















  • 1




    Just curious. Why do you want to do this?
    – DOK
    Oct 24 '08 at 13:41






  • 14




    To be able to log in as a different user.
    – Marko
    Oct 24 '08 at 14:08






  • 13




    @DOK - It's a standard social-hacking thing: users should be able to log out while leaving their browser open. Suppose one of your users accesses the site on a public machine? They need to log-off explicitly so that the next user can't access the site as them.
    – Keith
    Jun 9 '11 at 7:53










  • @DOK There is also the problem that it makes it impossible for the user to logout of the site. The server can clear the authorization cookie, and even the session cookie. But when the browser goes to load the / page, they will automatically be logged in again.
    – Ian Boyd
    May 11 '16 at 19:22










  • I using the method that send a fake request to logout, but it locks the user in customer since there is a strick limitation that 3 times login failed in AD. So, suggest using this method(send a fake request) with caution.
    – Qianchao Pan
    Jul 31 '17 at 3:32















up vote
233
down vote

favorite
105












Is it possible to log out user from a web site if he is using basic authentication?



Killing session is not enough, since, once user is authenticated, each request contains login info, so user is automatically logged in next time he/she access the site using the same credentials.



The only solution so far is to close browser, but that's not acceptable from the usability standpoint.










share|improve this question




















  • 1




    Just curious. Why do you want to do this?
    – DOK
    Oct 24 '08 at 13:41






  • 14




    To be able to log in as a different user.
    – Marko
    Oct 24 '08 at 14:08






  • 13




    @DOK - It's a standard social-hacking thing: users should be able to log out while leaving their browser open. Suppose one of your users accesses the site on a public machine? They need to log-off explicitly so that the next user can't access the site as them.
    – Keith
    Jun 9 '11 at 7:53










  • @DOK There is also the problem that it makes it impossible for the user to logout of the site. The server can clear the authorization cookie, and even the session cookie. But when the browser goes to load the / page, they will automatically be logged in again.
    – Ian Boyd
    May 11 '16 at 19:22










  • I using the method that send a fake request to logout, but it locks the user in customer since there is a strick limitation that 3 times login failed in AD. So, suggest using this method(send a fake request) with caution.
    – Qianchao Pan
    Jul 31 '17 at 3:32













up vote
233
down vote

favorite
105









up vote
233
down vote

favorite
105






105





Is it possible to log out user from a web site if he is using basic authentication?



Killing session is not enough, since, once user is authenticated, each request contains login info, so user is automatically logged in next time he/she access the site using the same credentials.



The only solution so far is to close browser, but that's not acceptable from the usability standpoint.










share|improve this question















Is it possible to log out user from a web site if he is using basic authentication?



Killing session is not enough, since, once user is authenticated, each request contains login info, so user is automatically logged in next time he/she access the site using the same credentials.



The only solution so far is to close browser, but that's not acceptable from the usability standpoint.







http authentication basic-authentication http-basic-authentication






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 16 '16 at 18:36









KyleMit

57.1k34234390




57.1k34234390










asked Oct 24 '08 at 13:21









Marko

21.7k1766103




21.7k1766103








  • 1




    Just curious. Why do you want to do this?
    – DOK
    Oct 24 '08 at 13:41






  • 14




    To be able to log in as a different user.
    – Marko
    Oct 24 '08 at 14:08






  • 13




    @DOK - It's a standard social-hacking thing: users should be able to log out while leaving their browser open. Suppose one of your users accesses the site on a public machine? They need to log-off explicitly so that the next user can't access the site as them.
    – Keith
    Jun 9 '11 at 7:53










  • @DOK There is also the problem that it makes it impossible for the user to logout of the site. The server can clear the authorization cookie, and even the session cookie. But when the browser goes to load the / page, they will automatically be logged in again.
    – Ian Boyd
    May 11 '16 at 19:22










  • I using the method that send a fake request to logout, but it locks the user in customer since there is a strick limitation that 3 times login failed in AD. So, suggest using this method(send a fake request) with caution.
    – Qianchao Pan
    Jul 31 '17 at 3:32














  • 1




    Just curious. Why do you want to do this?
    – DOK
    Oct 24 '08 at 13:41






  • 14




    To be able to log in as a different user.
    – Marko
    Oct 24 '08 at 14:08






  • 13




    @DOK - It's a standard social-hacking thing: users should be able to log out while leaving their browser open. Suppose one of your users accesses the site on a public machine? They need to log-off explicitly so that the next user can't access the site as them.
    – Keith
    Jun 9 '11 at 7:53










  • @DOK There is also the problem that it makes it impossible for the user to logout of the site. The server can clear the authorization cookie, and even the session cookie. But when the browser goes to load the / page, they will automatically be logged in again.
    – Ian Boyd
    May 11 '16 at 19:22










  • I using the method that send a fake request to logout, but it locks the user in customer since there is a strick limitation that 3 times login failed in AD. So, suggest using this method(send a fake request) with caution.
    – Qianchao Pan
    Jul 31 '17 at 3:32








1




1




Just curious. Why do you want to do this?
– DOK
Oct 24 '08 at 13:41




Just curious. Why do you want to do this?
– DOK
Oct 24 '08 at 13:41




14




14




To be able to log in as a different user.
– Marko
Oct 24 '08 at 14:08




To be able to log in as a different user.
– Marko
Oct 24 '08 at 14:08




13




13




@DOK - It's a standard social-hacking thing: users should be able to log out while leaving their browser open. Suppose one of your users accesses the site on a public machine? They need to log-off explicitly so that the next user can't access the site as them.
– Keith
Jun 9 '11 at 7:53




@DOK - It's a standard social-hacking thing: users should be able to log out while leaving their browser open. Suppose one of your users accesses the site on a public machine? They need to log-off explicitly so that the next user can't access the site as them.
– Keith
Jun 9 '11 at 7:53












@DOK There is also the problem that it makes it impossible for the user to logout of the site. The server can clear the authorization cookie, and even the session cookie. But when the browser goes to load the / page, they will automatically be logged in again.
– Ian Boyd
May 11 '16 at 19:22




@DOK There is also the problem that it makes it impossible for the user to logout of the site. The server can clear the authorization cookie, and even the session cookie. But when the browser goes to load the / page, they will automatically be logged in again.
– Ian Boyd
May 11 '16 at 19:22












I using the method that send a fake request to logout, but it locks the user in customer since there is a strick limitation that 3 times login failed in AD. So, suggest using this method(send a fake request) with caution.
– Qianchao Pan
Jul 31 '17 at 3:32




I using the method that send a fake request to logout, but it locks the user in customer since there is a strick limitation that 3 times login failed in AD. So, suggest using this method(send a fake request) with caution.
– Qianchao Pan
Jul 31 '17 at 3:32












18 Answers
18






active

oldest

votes

















up vote
146
down vote



accepted










Basic Authentication wasn't designed to manage logging out. You can do it, but not completely automatically.



What you have to do is have the user click a logout link, and send a ‘401 Unauthorized’ in response, using the same realm and at the same URL folder level as the normal 401 you send requesting a login.



They must be directed to input wrong credentials next, eg. a blank username-and-password, and in response you send back a “You have successfully logged out” page. The wrong/blank credentials will then overwrite the previous correct credentials.



In short, the logout script inverts the logic of the login script, only returning the success page if the user isn't passing the right credentials.



The question is whether the somewhat curious “don't enter your password” password box will meet user acceptance. Password managers that try to auto-fill the password can also get in the way here.



Edit to add in response to comment: re-log-in is a slightly different problem (unless you require a two-step logout/login obviously). You have to reject (401) the first attempt to access the relogin link, than accept the second (which presumably has a different username/password). There are a few ways you could do this. One would be to include the current username in the logout link (eg. /relogin?username), and reject when the credentials match the username.






share|improve this answer



















  • 2




    I'll try this approach. The point of logout (in this case) is to enable user to log in as different user, so it is perfectly acceptable solution. As for auto-fill password, it is up to user if he will use it or not. Thanks
    – Marko
    Oct 24 '08 at 14:07










  • Is this still the only way? I've done an ASP.Net MVC and jQuery implementation that works, but I'm still not happy with it: stackoverflow.com/questions/6277919
    – Keith
    Jun 9 '11 at 7:51










  • @Keith: Still only this and systemPAUSE's answer (which doesn't work on all browsers, but is smoother than the manual approach when it does work).
    – bobince
    Jun 9 '11 at 21:49








  • 12




    The W3C is so active on the HTML spec. But the HTTP spec is languishing. W3C should have fixed this problem about two decades ago. With the rise in use of REST services, a robust native authentication method is need of the day.
    – Dojo
    Dec 1 '14 at 13:38






  • 7




    This doesn't appear to work properly in Chrome 46 browsing on localhost. Chrome appears to keep both the old (correct) password and the new password which you specify. After navigating to the logout page, chrome correctly uses the new password UNTIL IT ENCOUNTERS A 401 UNAUTHORIZED ON A PAGE ON YOUR SITE. After the first 401, Chrome reverts back to the old (correct) password. So it really didn't delete the password in the first place it seems.
    – vancan1ty
    Jan 8 '16 at 22:10




















up vote
181
down vote



+200










An addition to the answer by bobince ...



With Ajax you can have your 'Logout' link/button wired to a Javascript function. Have this function send the XMLHttpRequest with a bad username and password. This should get back a 401. Then set document.location back to the pre-login page. This way, the user will never see the extra login dialog during logout, nor have to remember to put in bad credentials.






share|improve this answer

















  • 11




    Good hack, having the user manually enter bad credentials is probably not acceptable for most webapps.
    – BillMan
    Mar 28 '11 at 14:08






  • 1




    Just make sure the XMLHttpRequest isn't set to be asynchronous or you may find that the redirection via will take place before the logout request completes.
    – davidjb
    Mar 20 '14 at 5:54






  • 4




    You can use the same trick for login as well. That way you can customize the login dialog without having to change the server's authentication method. This article gives some good ideas: http://www.peej.co.uk/articles/http-auth-with-html-forms.html
    – Stijn de Witt
    Apr 1 '14 at 11:12






  • 1




    @davidjb Since synchronous requests are considered deprecated now, an alternative solution might be to redirect the user in the callback of the async request.
    – Hayden Schiff
    Jul 31 '15 at 20:20








  • 1




    David: chrome now permits this for XHRs, and I can confirm that it is still working in chrome canary. bugs.chromium.org/p/chromium/issues/detail?id=435547
    – CpnCrunch
    May 25 '17 at 17:49


















up vote
168
down vote













Have the user click on a link to https://log:out@example.com/. That will overwrite existing credentials with invalid ones; logging them out.






share|improve this answer



















  • 17




    Why does this one not get more upvotes? Seems like a simple and working solution to me. Are there any known problems with this approach?
    – amoebe
    Jan 17 '14 at 14:00






  • 24




    This would no longer work in Chrome, which for security reasons ignores credentials in a URL.
    – Thom
    Jun 6 '14 at 9:49






  • 5




    This Worked for me :) I am using Chrome Version 32.0.1700.102
    – abottoni
    Aug 6 '14 at 13:28






  • 5




    problem: using version 39.0 of chrome, When I click the logout link via this method, Chrome remembers the bad login credentials, and prompts for new login credentials on every page load, until I go to example.com without any specified login credentials, to clear chrome's memory.
    – Scott
    Jan 23 '15 at 4:08






  • 4




    Hi, I cannot use it for https on Chrome.
    – thienkhoi tran
    Aug 28 '15 at 9:51


















up vote
57
down vote













You can do it entirely in JavaScript:



IE has (for a long time) standard API for clearing Basic Authentication cache:



document.execCommand("ClearAuthenticationCache")


Should return true when it works. Returns either false, undefined or blows up on other browsers.



New browsers (as of Dec 2012: Chrome, FireFox, Safari) have "magic" behavior. If they see a successful basic auth request with any bogus other username (let's say logout) they clear the credentials cache and possibly set it for that new bogus user name, which you need to make sure is not a valid user name for viewing content.



Basic example of that is:



var p = window.location.protocol + '//'
// current location must return 200 OK for this GET
window.location = window.location.href.replace(p, p + 'logout:password@')


An "asynchronous" way of doing the above is to do an AJAX call utilizing the logout username. Example:



(function(safeLocation){
var outcome, u, m = "You should be logged out now.";
// IE has a simple solution for it - API:
try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
// Other browsers need a larger solution - AJAX call with special user name - 'logout'.
if (!outcome) {
// Let's create an xmlhttp object
outcome = (function(x){
if (x) {
// the reason we use "random" value for password is
// that browsers cache requests. changing
// password effectively behaves like cache-busing.
x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
x.send("")
// x.abort()
return 1 // this is **speculative** "We are done."
} else {
return
}
})(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
}
if (!outcome) {
m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
}
alert(m)
// return !!outcome
})(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)


You can make it a bookmarklet too:



javascript:(function(c){var a,b="You should be logged out now.";try{a=document.execCommand("ClearAuthenticationCache")}catch(d){}a||((a=window.XMLHttpRequest?new window.XMLHttpRequest:window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):void 0)?(a.open("HEAD",c||location.href,!0,"logout",(new Date).getTime().toString()),a.send(""),a=1):a=void 0);a||(b="Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.");alert(b)})(/*pass safeLocation here if you need*/);






share|improve this answer



















  • 1




    Does this require special server-side handling of the logout username and/or logout URL?
    – ulidtko
    Oct 7 '13 at 19:30






  • 1




    @ulidtko No, it shouldn't - all handling is client-side. The only situation that would need special handling is if a user called logout happens to exist and happens to have the generated password. In that almost impossibly-rare case, change the user ID to one that won't exist in your system.
    – davidjb
    Mar 20 '14 at 5:58






  • 1




    I used the bookmarklet above today and I works well.
    – David Gleba
    May 13 '15 at 12:51










  • I used this and it worked for Chrome and FF. I only had to do an extra "GET" on my logout.php page to clear the $_SESSION.
    – urban
    Oct 9 '15 at 10:08










  • The bookmarklet works on Edge, too. Simply use with <a href='javascript:......need*/);'>Logout</a>
    – Eric
    Nov 30 '15 at 6:57




















up vote
14
down vote













The following function is confirmed working for Firefox 40, Chrome 44, Opera 31 and IE 11.
Bowser is used for browser detection, jQuery is also used.


- secUrl is the url to a password protected area from which to log out.

- redirUrl is the url to a non password protected area (logout success page).


- you might wish to increase the redirect timer (currently 200ms).






function logout(secUrl, redirUrl) {
if (bowser.msie) {
document.execCommand('ClearAuthenticationCache', 'false');
} else if (bowser.gecko) {
$.ajax({
async: false,
url: secUrl,
type: 'GET',
username: 'logout'
});
} else if (bowser.webkit) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", secUrl, true);
xmlhttp.setRequestHeader("Authorization", "Basic logout");
xmlhttp.send();
} else {
alert("Logging out automatically is unsupported for " + bowser.name
+ "nYou must close the browser to log out.");
}
setTimeout(function () {
window.location.href = redirUrl;
}, 200);
}








share|improve this answer





















  • this is the most comprehensive answer
    – belidzs
    Oct 21 '15 at 14:51










  • Is there any reason for the $.ajax variant being synchronous (async: false) and the xmlhttp variant being asynchronous (the true in open())?
    – Bowi
    Sep 14 '17 at 13:34










  • Chrome now uses the rendering engine Blink, so you have to change (bowser.gecko) to (bowser.gecko || bowser.blink).
    – Bowi
    Sep 15 '17 at 14:10






  • 1




    Why does gecko/blink use $.ajax and webkit use new XMLHttpRequest? Shouldn't gecko/blink be able to do XMLHttpRequest and webkit be able to do $.ajax too? I'm confused.
    – RemyNL
    Oct 31 at 12:13


















up vote
10
down vote













This isn't directly possible with Basic-Authentication.



There's no mechanism in the HTTP specification for the server to tell the browser to stop sending the credentials that the user already presented.



There are "hacks" (see other answers) typically involving using XMLHttpRequest to send an HTTP request with incorrect credentials to overwrite the ones originally supplied.






share|improve this answer



















  • 11




    In Theory. Practice proves otherwise as can be seen from the other answers.
    – Stijn de Witt
    Apr 1 '14 at 11:14






  • 2




    And as you can also see from the other answers, not in a reliable, consistent and fail-safe way !
    – jplandrain
    Aug 21 '17 at 9:55


















up vote
9
down vote













Here's a very simple Javascript example using jQuery:



function logout(to_url) {
var out = window.location.href.replace(/:///, '://log:out@');

jQuery.get(out).error(function() {
window.location = to_url;
});
}


This log user out without showing him the browser log-in box again, then redirect him to a logged out page






share|improve this answer





















  • As of jQuery 1.8, the .error() method is deprecated and removed from 3.0 Use .fail() instead.
    – RemyNL
    Oct 31 at 11:27


















up vote
6
down vote













It's actually pretty simple.



Just visit the following in your browser and use wrong credentials:
http://username:password@yourdomain.com



That should "log you out".






share|improve this answer





















  • But the user have to be a REAL user, othervise I got "401 Unauthorized", but using BACK button I am able to continue work as a previously logged user. Tested on Abyss web server X1 (2.11.1)
    – user2956477
    Dec 29 '16 at 10:39






  • 1




    Duplicate answer (see Matthew Welborn's above).
    – Skippy le Grand Gourou
    Sep 12 at 9:53


















up vote
5
down vote













This is working for IE/Netscape/Chrome :



      function ClearAuthentication(LogOffPage) 
{
var IsInternetExplorer = false;

try
{
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("msie") != -1) { IsInternetExplorer = true; }
}
catch(e)
{
IsInternetExplorer = false;
};

if (IsInternetExplorer)
{
// Logoff Internet Explorer
document.execCommand("ClearAuthenticationCache");
window.location = LogOffPage;
}
else
{
// Logoff every other browsers
$.ajax({
username: 'unknown',
password: 'WrongPassword',
url: './cgi-bin/PrimoCgi',
type: 'GET',
beforeSend: function(xhr)
{
xhr.setRequestHeader("Authorization", "Basic AAAAAAAAAAAAAAAAAAA=");
},

error: function(err)
{
window.location = LogOffPage;
}
});
}
}


$(document).ready(function ()
{
$('#Btn1').click(function ()
{
// Call Clear Authentication
ClearAuthentication("force_logout.html");
});
});





share|improve this answer




























    up vote
    2
    down vote













    function logout() {
    var userAgent = navigator.userAgent.toLowerCase();

    if (userAgent.indexOf("msie") != -1) {
    document.execCommand("ClearAuthenticationCache", false);
    }

    xhr_objectCarte = null;

    if(window.XMLHttpRequest)
    xhr_object = new XMLHttpRequest();
    else if(window.ActiveXObject)
    xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
    else
    alert ("Your browser doesn't support XMLHTTPREQUEST");

    xhr_object.open ('GET', 'http://yourserver.com/rep/index.php', false, 'username', 'password');
    xhr_object.send ("");
    xhr_object = null;

    document.location = 'http://yourserver.com';
    return false;
    }





    share|improve this answer




























      up vote
      2
      down vote













       function logout(url){
      var str = url.replace("http://", "http://" + new Date().getTime() + "@");
      var xmlhttp;
      if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
      else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4) location.reload();
      }
      xmlhttp.open("GET",str,true);
      xmlhttp.setRequestHeader("Authorization","Basic xxxxxxxxxx")
      xmlhttp.send();
      return false;
      }





      share|improve this answer




























        up vote
        1
        down vote













        add this to your application :



        @app.route('/logout')
        def logout():
        return ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'})





        share|improve this answer





















        • better to use this return : return('Logout', 401)
          – Amir Mofakhar
          Sep 18 '15 at 13:35


















        up vote
        1
        down vote













        All you need is redirect user on some logout URL and return 401 Unauthorized error on it. On error page (which must be accessible without basic auth) you need to provide a full link to your home page (including scheme and hostname). User will click this link and browser will ask for credentials again.



        Example for Nginx:



        location /logout {
        return 401;
        }

        error_page 401 /errors/401.html;

        location /errors {
        auth_basic off;
        ssi on;
        ssi_types text/html;
        alias /home/user/errors;
        }


        Error page /home/user/errors/401.html:



        <!DOCTYPE html>
        <p>You're not authorised. <a href="<!--# echo var="scheme" -->://<!--# echo var="host" -->/">Login</a>.</p>





        share|improve this answer




























          up vote
          1
          down vote













          Based on what I read above I got a simple solution that works on any browser:



          1) on you logout page you call an ajax to your login back end. Your login back end must accept logout user. Once the back end accept, the browser clear the current user and assumes the "logout" user.



          $.ajax({
          async: false,
          url: 'http://your_login_backend',
          type: 'GET',
          username: 'logout'
          });

          setTimeout(function () {
          window.location.href = 'http://normal_index';
          }, 200);


          2) Now when the user got back to the normal index file it will try to automatic enter in the system with the user "logout", on this second time you must block it by reply with 401 to invoke the login/password dialog.



          3) There are many ways to do that, I created two login back ends, one that accepts the logout user and one that doesn't. My normal login page use the one that doesn't accept, my logout page use the one that accepts it.






          share|improve this answer






























            up vote
            0
            down vote














            • use a session ID (cookie)

            • invalidate the session ID on the server

            • Don't accept users with invalid session IDs






            share|improve this answer





















            • It's also good to offer Basic Authentication as a backup login scheme for when cookies aren't available.
              – bobince
              Oct 24 '08 at 13:35






            • 6




              Invalidating session doesn't work, see other comments.
              – Marko
              Oct 24 '08 at 14:08


















            up vote
            0
            down vote













            This JavaScript must be working for all latest version browsers:



            //Detect Browser
            var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
            // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
            var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
            var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
            // At least Safari 3+: "[object HTMLElementConstructor]"
            var isChrome = !!window.chrome && !isOpera; // Chrome 1+
            var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
            var Host = window.location.host;


            //Clear Basic Realm Authentication
            if(isIE){
            //IE
            document.execCommand("ClearAuthenticationCache");
            window.location = '/';
            }
            else if(isSafari)
            {//Safari. but this works mostly on all browser except chrome
            (function(safeLocation){
            var outcome, u, m = "You should be logged out now.";
            // IE has a simple solution for it - API:
            try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
            // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
            if (!outcome) {
            // Let's create an xmlhttp object
            outcome = (function(x){
            if (x) {
            // the reason we use "random" value for password is
            // that browsers cache requests. changing
            // password effectively behaves like cache-busing.
            x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
            x.send("");
            // x.abort()
            return 1 // this is **speculative** "We are done."
            } else {
            return
            }
            })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
            }
            if (!outcome) {
            m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
            }
            alert(m);
            window.location = '/';
            // return !!outcome
            })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)
            }
            else{
            //Firefox,Chrome
            window.location = 'http://log:out@'+Host+'/';
            }





            share|improve this answer




























              up vote
              0
              down vote













              I updated mthoring's solution for modern Chrome versions:



              function logout(secUrl, redirUrl) {
              if (bowser.msie) {
              document.execCommand('ClearAuthenticationCache', 'false');
              } else if (bowser.gecko) {
              $.ajax({
              async: false,
              url: secUrl,
              type: 'GET',
              username: 'logout'
              });
              } else if (bowser.webkit || bowser.chrome) {
              var xmlhttp = new XMLHttpRequest();
              xmlhttp.open("GET", secUrl, true);
              xmlhttp.setRequestHeader("Authorization", "Basic logout");
              xmlhttp.send();
              } else {
              // http://stackoverflow.com/questions/5957822/how-to-clear-basic-authentication-details-in-chrome
              redirUrl = url.replace('http://', 'http://' + new Date().getTime() + '@');
              }
              setTimeout(function () {
              window.location.href = redirUrl;
              }, 200);
              }





              share|improve this answer




























                up vote
                0
                down vote















                    function logout(secUrl, redirUrl) {
                if (bowser.msie) {
                document.execCommand('ClearAuthenticationCache', 'false');
                } else if (bowser.gecko) {
                $.ajax({
                async: false,
                url: secUrl,
                type: 'GET',
                username: 'logout'
                });
                } else if (bowser.webkit) {
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", secUrl, true);
                xmlhttp.setRequestHeader("Authorization", "Basic logout");
                xmlhttp.send();
                } else {
                alert("Logging out automatically is unsupported for " + bowser.name
                + "nYou must close the browser to log out.");
                }
                setTimeout(function () {
                window.location.href = redirUrl;
                }, 200);
                }






                I tried using the above in the following way.



                ?php
                ob_start();
                session_start();
                require_once 'dbconnect.php';

                // if session is not set this will redirect to login page
                if( !isset($_SESSION['user']) ) {
                header("Location: index.php");
                exit;
                }
                // select loggedin users detail
                $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
                $userRow=mysql_fetch_array($res);
                ?>
                <!DOCTYPE html>
                <html>
                <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <title>Welcome - <?php echo $userRow['userEmail']; ?></title>
                <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
                <link rel="stylesheet" href="style.css" type="text/css" />

                <script src="assets/js/bowser.min.js"></script>
                <script>
                //function logout(secUrl, redirUrl)
                //bowser = require('bowser');
                function logout(secUrl, redirUrl) {
                alert(redirUrl);
                if (bowser.msie) {
                document.execCommand('ClearAuthenticationCache', 'false');
                } else if (bowser.gecko) {
                $.ajax({
                async: false,
                url: secUrl,
                type: 'GET',
                username: 'logout'
                });
                } else if (bowser.webkit) {
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", secUrl, true);
                xmlhttp.setRequestHeader("Authorization", "Basic logout");
                xmlhttp.send();
                } else {
                alert("Logging out automatically is unsupported for " + bowser.name
                + "nYou must close the browser to log out.");
                }
                window.location.assign(redirUrl);
                /*setTimeout(function () {
                window.location.href = redirUrl;
                }, 200);*/
                }


                function f1()
                {
                alert("f1 called");
                //form validation that recalls the page showing with supplied inputs.
                }
                </script>
                </head>
                <body>

                <nav class="navbar navbar-default navbar-fixed-top">
                <div class="container">
                <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="http://www.codingcage.com">Coding Cage</a>
                </div>
                <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                <li class="active"><a href="http://www.codingcage.com/2015/01/user-registration-and-login-script-using-php-mysql.html">Back to Article</a></li>
                <li><a href="http://www.codingcage.com/search/label/jQuery">jQuery</a></li>
                <li><a href="http://www.codingcage.com/search/label/PHP">PHP</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right">

                <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                <span class="glyphicon glyphicon-user"></span>&nbsp;Hi' <?php echo $userRow['userEmail']; ?>&nbsp;<span class="caret"></span></a>
                <ul class="dropdown-menu">
                <li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Sign Out</a></li>
                </ul>
                </li>
                </ul>
                </div><!--/.nav-collapse -->
                </div>
                </nav>

                <div id="wrapper">

                <div class="container">

                <div class="page-header">
                <h3>Coding Cage - Programming Blog</h3>
                </div>

                <div class="row">
                <div class="col-lg-12" id="div_logout">
                <h1 onclick="logout(window.location.href, 'www.espncricinfo.com')">MichaelA1S1! Click here to see log out functionality upon click inside div</h1>
                </div>
                </div>

                </div>

                </div>

                <script src="assets/jquery-1.11.3-jquery.min.js"></script>
                <script src="assets/js/bootstrap.min.js"></script>


                </body>
                </html>
                <?php ob_end_flush(); ?>


                But it only redirects you to new location. No logout.






                share|improve this answer






















                  protected by Community Aug 3 '17 at 16:52



                  Thank you for your interest in this question.
                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                  Would you like to answer one of these unanswered questions instead?














                  18 Answers
                  18






                  active

                  oldest

                  votes








                  18 Answers
                  18






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes








                  up vote
                  146
                  down vote



                  accepted










                  Basic Authentication wasn't designed to manage logging out. You can do it, but not completely automatically.



                  What you have to do is have the user click a logout link, and send a ‘401 Unauthorized’ in response, using the same realm and at the same URL folder level as the normal 401 you send requesting a login.



                  They must be directed to input wrong credentials next, eg. a blank username-and-password, and in response you send back a “You have successfully logged out” page. The wrong/blank credentials will then overwrite the previous correct credentials.



                  In short, the logout script inverts the logic of the login script, only returning the success page if the user isn't passing the right credentials.



                  The question is whether the somewhat curious “don't enter your password” password box will meet user acceptance. Password managers that try to auto-fill the password can also get in the way here.



                  Edit to add in response to comment: re-log-in is a slightly different problem (unless you require a two-step logout/login obviously). You have to reject (401) the first attempt to access the relogin link, than accept the second (which presumably has a different username/password). There are a few ways you could do this. One would be to include the current username in the logout link (eg. /relogin?username), and reject when the credentials match the username.






                  share|improve this answer



















                  • 2




                    I'll try this approach. The point of logout (in this case) is to enable user to log in as different user, so it is perfectly acceptable solution. As for auto-fill password, it is up to user if he will use it or not. Thanks
                    – Marko
                    Oct 24 '08 at 14:07










                  • Is this still the only way? I've done an ASP.Net MVC and jQuery implementation that works, but I'm still not happy with it: stackoverflow.com/questions/6277919
                    – Keith
                    Jun 9 '11 at 7:51










                  • @Keith: Still only this and systemPAUSE's answer (which doesn't work on all browsers, but is smoother than the manual approach when it does work).
                    – bobince
                    Jun 9 '11 at 21:49








                  • 12




                    The W3C is so active on the HTML spec. But the HTTP spec is languishing. W3C should have fixed this problem about two decades ago. With the rise in use of REST services, a robust native authentication method is need of the day.
                    – Dojo
                    Dec 1 '14 at 13:38






                  • 7




                    This doesn't appear to work properly in Chrome 46 browsing on localhost. Chrome appears to keep both the old (correct) password and the new password which you specify. After navigating to the logout page, chrome correctly uses the new password UNTIL IT ENCOUNTERS A 401 UNAUTHORIZED ON A PAGE ON YOUR SITE. After the first 401, Chrome reverts back to the old (correct) password. So it really didn't delete the password in the first place it seems.
                    – vancan1ty
                    Jan 8 '16 at 22:10

















                  up vote
                  146
                  down vote



                  accepted










                  Basic Authentication wasn't designed to manage logging out. You can do it, but not completely automatically.



                  What you have to do is have the user click a logout link, and send a ‘401 Unauthorized’ in response, using the same realm and at the same URL folder level as the normal 401 you send requesting a login.



                  They must be directed to input wrong credentials next, eg. a blank username-and-password, and in response you send back a “You have successfully logged out” page. The wrong/blank credentials will then overwrite the previous correct credentials.



                  In short, the logout script inverts the logic of the login script, only returning the success page if the user isn't passing the right credentials.



                  The question is whether the somewhat curious “don't enter your password” password box will meet user acceptance. Password managers that try to auto-fill the password can also get in the way here.



                  Edit to add in response to comment: re-log-in is a slightly different problem (unless you require a two-step logout/login obviously). You have to reject (401) the first attempt to access the relogin link, than accept the second (which presumably has a different username/password). There are a few ways you could do this. One would be to include the current username in the logout link (eg. /relogin?username), and reject when the credentials match the username.






                  share|improve this answer



















                  • 2




                    I'll try this approach. The point of logout (in this case) is to enable user to log in as different user, so it is perfectly acceptable solution. As for auto-fill password, it is up to user if he will use it or not. Thanks
                    – Marko
                    Oct 24 '08 at 14:07










                  • Is this still the only way? I've done an ASP.Net MVC and jQuery implementation that works, but I'm still not happy with it: stackoverflow.com/questions/6277919
                    – Keith
                    Jun 9 '11 at 7:51










                  • @Keith: Still only this and systemPAUSE's answer (which doesn't work on all browsers, but is smoother than the manual approach when it does work).
                    – bobince
                    Jun 9 '11 at 21:49








                  • 12




                    The W3C is so active on the HTML spec. But the HTTP spec is languishing. W3C should have fixed this problem about two decades ago. With the rise in use of REST services, a robust native authentication method is need of the day.
                    – Dojo
                    Dec 1 '14 at 13:38






                  • 7




                    This doesn't appear to work properly in Chrome 46 browsing on localhost. Chrome appears to keep both the old (correct) password and the new password which you specify. After navigating to the logout page, chrome correctly uses the new password UNTIL IT ENCOUNTERS A 401 UNAUTHORIZED ON A PAGE ON YOUR SITE. After the first 401, Chrome reverts back to the old (correct) password. So it really didn't delete the password in the first place it seems.
                    – vancan1ty
                    Jan 8 '16 at 22:10















                  up vote
                  146
                  down vote



                  accepted







                  up vote
                  146
                  down vote



                  accepted






                  Basic Authentication wasn't designed to manage logging out. You can do it, but not completely automatically.



                  What you have to do is have the user click a logout link, and send a ‘401 Unauthorized’ in response, using the same realm and at the same URL folder level as the normal 401 you send requesting a login.



                  They must be directed to input wrong credentials next, eg. a blank username-and-password, and in response you send back a “You have successfully logged out” page. The wrong/blank credentials will then overwrite the previous correct credentials.



                  In short, the logout script inverts the logic of the login script, only returning the success page if the user isn't passing the right credentials.



                  The question is whether the somewhat curious “don't enter your password” password box will meet user acceptance. Password managers that try to auto-fill the password can also get in the way here.



                  Edit to add in response to comment: re-log-in is a slightly different problem (unless you require a two-step logout/login obviously). You have to reject (401) the first attempt to access the relogin link, than accept the second (which presumably has a different username/password). There are a few ways you could do this. One would be to include the current username in the logout link (eg. /relogin?username), and reject when the credentials match the username.






                  share|improve this answer














                  Basic Authentication wasn't designed to manage logging out. You can do it, but not completely automatically.



                  What you have to do is have the user click a logout link, and send a ‘401 Unauthorized’ in response, using the same realm and at the same URL folder level as the normal 401 you send requesting a login.



                  They must be directed to input wrong credentials next, eg. a blank username-and-password, and in response you send back a “You have successfully logged out” page. The wrong/blank credentials will then overwrite the previous correct credentials.



                  In short, the logout script inverts the logic of the login script, only returning the success page if the user isn't passing the right credentials.



                  The question is whether the somewhat curious “don't enter your password” password box will meet user acceptance. Password managers that try to auto-fill the password can also get in the way here.



                  Edit to add in response to comment: re-log-in is a slightly different problem (unless you require a two-step logout/login obviously). You have to reject (401) the first attempt to access the relogin link, than accept the second (which presumably has a different username/password). There are a few ways you could do this. One would be to include the current username in the logout link (eg. /relogin?username), and reject when the credentials match the username.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 24 '08 at 15:06

























                  answered Oct 24 '08 at 13:33









                  bobince

                  439k89564765




                  439k89564765








                  • 2




                    I'll try this approach. The point of logout (in this case) is to enable user to log in as different user, so it is perfectly acceptable solution. As for auto-fill password, it is up to user if he will use it or not. Thanks
                    – Marko
                    Oct 24 '08 at 14:07










                  • Is this still the only way? I've done an ASP.Net MVC and jQuery implementation that works, but I'm still not happy with it: stackoverflow.com/questions/6277919
                    – Keith
                    Jun 9 '11 at 7:51










                  • @Keith: Still only this and systemPAUSE's answer (which doesn't work on all browsers, but is smoother than the manual approach when it does work).
                    – bobince
                    Jun 9 '11 at 21:49








                  • 12




                    The W3C is so active on the HTML spec. But the HTTP spec is languishing. W3C should have fixed this problem about two decades ago. With the rise in use of REST services, a robust native authentication method is need of the day.
                    – Dojo
                    Dec 1 '14 at 13:38






                  • 7




                    This doesn't appear to work properly in Chrome 46 browsing on localhost. Chrome appears to keep both the old (correct) password and the new password which you specify. After navigating to the logout page, chrome correctly uses the new password UNTIL IT ENCOUNTERS A 401 UNAUTHORIZED ON A PAGE ON YOUR SITE. After the first 401, Chrome reverts back to the old (correct) password. So it really didn't delete the password in the first place it seems.
                    – vancan1ty
                    Jan 8 '16 at 22:10
















                  • 2




                    I'll try this approach. The point of logout (in this case) is to enable user to log in as different user, so it is perfectly acceptable solution. As for auto-fill password, it is up to user if he will use it or not. Thanks
                    – Marko
                    Oct 24 '08 at 14:07










                  • Is this still the only way? I've done an ASP.Net MVC and jQuery implementation that works, but I'm still not happy with it: stackoverflow.com/questions/6277919
                    – Keith
                    Jun 9 '11 at 7:51










                  • @Keith: Still only this and systemPAUSE's answer (which doesn't work on all browsers, but is smoother than the manual approach when it does work).
                    – bobince
                    Jun 9 '11 at 21:49








                  • 12




                    The W3C is so active on the HTML spec. But the HTTP spec is languishing. W3C should have fixed this problem about two decades ago. With the rise in use of REST services, a robust native authentication method is need of the day.
                    – Dojo
                    Dec 1 '14 at 13:38






                  • 7




                    This doesn't appear to work properly in Chrome 46 browsing on localhost. Chrome appears to keep both the old (correct) password and the new password which you specify. After navigating to the logout page, chrome correctly uses the new password UNTIL IT ENCOUNTERS A 401 UNAUTHORIZED ON A PAGE ON YOUR SITE. After the first 401, Chrome reverts back to the old (correct) password. So it really didn't delete the password in the first place it seems.
                    – vancan1ty
                    Jan 8 '16 at 22:10










                  2




                  2




                  I'll try this approach. The point of logout (in this case) is to enable user to log in as different user, so it is perfectly acceptable solution. As for auto-fill password, it is up to user if he will use it or not. Thanks
                  – Marko
                  Oct 24 '08 at 14:07




                  I'll try this approach. The point of logout (in this case) is to enable user to log in as different user, so it is perfectly acceptable solution. As for auto-fill password, it is up to user if he will use it or not. Thanks
                  – Marko
                  Oct 24 '08 at 14:07












                  Is this still the only way? I've done an ASP.Net MVC and jQuery implementation that works, but I'm still not happy with it: stackoverflow.com/questions/6277919
                  – Keith
                  Jun 9 '11 at 7:51




                  Is this still the only way? I've done an ASP.Net MVC and jQuery implementation that works, but I'm still not happy with it: stackoverflow.com/questions/6277919
                  – Keith
                  Jun 9 '11 at 7:51












                  @Keith: Still only this and systemPAUSE's answer (which doesn't work on all browsers, but is smoother than the manual approach when it does work).
                  – bobince
                  Jun 9 '11 at 21:49






                  @Keith: Still only this and systemPAUSE's answer (which doesn't work on all browsers, but is smoother than the manual approach when it does work).
                  – bobince
                  Jun 9 '11 at 21:49






                  12




                  12




                  The W3C is so active on the HTML spec. But the HTTP spec is languishing. W3C should have fixed this problem about two decades ago. With the rise in use of REST services, a robust native authentication method is need of the day.
                  – Dojo
                  Dec 1 '14 at 13:38




                  The W3C is so active on the HTML spec. But the HTTP spec is languishing. W3C should have fixed this problem about two decades ago. With the rise in use of REST services, a robust native authentication method is need of the day.
                  – Dojo
                  Dec 1 '14 at 13:38




                  7




                  7




                  This doesn't appear to work properly in Chrome 46 browsing on localhost. Chrome appears to keep both the old (correct) password and the new password which you specify. After navigating to the logout page, chrome correctly uses the new password UNTIL IT ENCOUNTERS A 401 UNAUTHORIZED ON A PAGE ON YOUR SITE. After the first 401, Chrome reverts back to the old (correct) password. So it really didn't delete the password in the first place it seems.
                  – vancan1ty
                  Jan 8 '16 at 22:10






                  This doesn't appear to work properly in Chrome 46 browsing on localhost. Chrome appears to keep both the old (correct) password and the new password which you specify. After navigating to the logout page, chrome correctly uses the new password UNTIL IT ENCOUNTERS A 401 UNAUTHORIZED ON A PAGE ON YOUR SITE. After the first 401, Chrome reverts back to the old (correct) password. So it really didn't delete the password in the first place it seems.
                  – vancan1ty
                  Jan 8 '16 at 22:10














                  up vote
                  181
                  down vote



                  +200










                  An addition to the answer by bobince ...



                  With Ajax you can have your 'Logout' link/button wired to a Javascript function. Have this function send the XMLHttpRequest with a bad username and password. This should get back a 401. Then set document.location back to the pre-login page. This way, the user will never see the extra login dialog during logout, nor have to remember to put in bad credentials.






                  share|improve this answer

















                  • 11




                    Good hack, having the user manually enter bad credentials is probably not acceptable for most webapps.
                    – BillMan
                    Mar 28 '11 at 14:08






                  • 1




                    Just make sure the XMLHttpRequest isn't set to be asynchronous or you may find that the redirection via will take place before the logout request completes.
                    – davidjb
                    Mar 20 '14 at 5:54






                  • 4




                    You can use the same trick for login as well. That way you can customize the login dialog without having to change the server's authentication method. This article gives some good ideas: http://www.peej.co.uk/articles/http-auth-with-html-forms.html
                    – Stijn de Witt
                    Apr 1 '14 at 11:12






                  • 1




                    @davidjb Since synchronous requests are considered deprecated now, an alternative solution might be to redirect the user in the callback of the async request.
                    – Hayden Schiff
                    Jul 31 '15 at 20:20








                  • 1




                    David: chrome now permits this for XHRs, and I can confirm that it is still working in chrome canary. bugs.chromium.org/p/chromium/issues/detail?id=435547
                    – CpnCrunch
                    May 25 '17 at 17:49















                  up vote
                  181
                  down vote



                  +200










                  An addition to the answer by bobince ...



                  With Ajax you can have your 'Logout' link/button wired to a Javascript function. Have this function send the XMLHttpRequest with a bad username and password. This should get back a 401. Then set document.location back to the pre-login page. This way, the user will never see the extra login dialog during logout, nor have to remember to put in bad credentials.






                  share|improve this answer

















                  • 11




                    Good hack, having the user manually enter bad credentials is probably not acceptable for most webapps.
                    – BillMan
                    Mar 28 '11 at 14:08






                  • 1




                    Just make sure the XMLHttpRequest isn't set to be asynchronous or you may find that the redirection via will take place before the logout request completes.
                    – davidjb
                    Mar 20 '14 at 5:54






                  • 4




                    You can use the same trick for login as well. That way you can customize the login dialog without having to change the server's authentication method. This article gives some good ideas: http://www.peej.co.uk/articles/http-auth-with-html-forms.html
                    – Stijn de Witt
                    Apr 1 '14 at 11:12






                  • 1




                    @davidjb Since synchronous requests are considered deprecated now, an alternative solution might be to redirect the user in the callback of the async request.
                    – Hayden Schiff
                    Jul 31 '15 at 20:20








                  • 1




                    David: chrome now permits this for XHRs, and I can confirm that it is still working in chrome canary. bugs.chromium.org/p/chromium/issues/detail?id=435547
                    – CpnCrunch
                    May 25 '17 at 17:49













                  up vote
                  181
                  down vote



                  +200







                  up vote
                  181
                  down vote



                  +200




                  +200




                  An addition to the answer by bobince ...



                  With Ajax you can have your 'Logout' link/button wired to a Javascript function. Have this function send the XMLHttpRequest with a bad username and password. This should get back a 401. Then set document.location back to the pre-login page. This way, the user will never see the extra login dialog during logout, nor have to remember to put in bad credentials.






                  share|improve this answer












                  An addition to the answer by bobince ...



                  With Ajax you can have your 'Logout' link/button wired to a Javascript function. Have this function send the XMLHttpRequest with a bad username and password. This should get back a 401. Then set document.location back to the pre-login page. This way, the user will never see the extra login dialog during logout, nor have to remember to put in bad credentials.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 29 '09 at 18:56









                  system PAUSE

                  24.3k175458




                  24.3k175458








                  • 11




                    Good hack, having the user manually enter bad credentials is probably not acceptable for most webapps.
                    – BillMan
                    Mar 28 '11 at 14:08






                  • 1




                    Just make sure the XMLHttpRequest isn't set to be asynchronous or you may find that the redirection via will take place before the logout request completes.
                    – davidjb
                    Mar 20 '14 at 5:54






                  • 4




                    You can use the same trick for login as well. That way you can customize the login dialog without having to change the server's authentication method. This article gives some good ideas: http://www.peej.co.uk/articles/http-auth-with-html-forms.html
                    – Stijn de Witt
                    Apr 1 '14 at 11:12






                  • 1




                    @davidjb Since synchronous requests are considered deprecated now, an alternative solution might be to redirect the user in the callback of the async request.
                    – Hayden Schiff
                    Jul 31 '15 at 20:20








                  • 1




                    David: chrome now permits this for XHRs, and I can confirm that it is still working in chrome canary. bugs.chromium.org/p/chromium/issues/detail?id=435547
                    – CpnCrunch
                    May 25 '17 at 17:49














                  • 11




                    Good hack, having the user manually enter bad credentials is probably not acceptable for most webapps.
                    – BillMan
                    Mar 28 '11 at 14:08






                  • 1




                    Just make sure the XMLHttpRequest isn't set to be asynchronous or you may find that the redirection via will take place before the logout request completes.
                    – davidjb
                    Mar 20 '14 at 5:54






                  • 4




                    You can use the same trick for login as well. That way you can customize the login dialog without having to change the server's authentication method. This article gives some good ideas: http://www.peej.co.uk/articles/http-auth-with-html-forms.html
                    – Stijn de Witt
                    Apr 1 '14 at 11:12






                  • 1




                    @davidjb Since synchronous requests are considered deprecated now, an alternative solution might be to redirect the user in the callback of the async request.
                    – Hayden Schiff
                    Jul 31 '15 at 20:20








                  • 1




                    David: chrome now permits this for XHRs, and I can confirm that it is still working in chrome canary. bugs.chromium.org/p/chromium/issues/detail?id=435547
                    – CpnCrunch
                    May 25 '17 at 17:49








                  11




                  11




                  Good hack, having the user manually enter bad credentials is probably not acceptable for most webapps.
                  – BillMan
                  Mar 28 '11 at 14:08




                  Good hack, having the user manually enter bad credentials is probably not acceptable for most webapps.
                  – BillMan
                  Mar 28 '11 at 14:08




                  1




                  1




                  Just make sure the XMLHttpRequest isn't set to be asynchronous or you may find that the redirection via will take place before the logout request completes.
                  – davidjb
                  Mar 20 '14 at 5:54




                  Just make sure the XMLHttpRequest isn't set to be asynchronous or you may find that the redirection via will take place before the logout request completes.
                  – davidjb
                  Mar 20 '14 at 5:54




                  4




                  4




                  You can use the same trick for login as well. That way you can customize the login dialog without having to change the server's authentication method. This article gives some good ideas: http://www.peej.co.uk/articles/http-auth-with-html-forms.html
                  – Stijn de Witt
                  Apr 1 '14 at 11:12




                  You can use the same trick for login as well. That way you can customize the login dialog without having to change the server's authentication method. This article gives some good ideas: http://www.peej.co.uk/articles/http-auth-with-html-forms.html
                  – Stijn de Witt
                  Apr 1 '14 at 11:12




                  1




                  1




                  @davidjb Since synchronous requests are considered deprecated now, an alternative solution might be to redirect the user in the callback of the async request.
                  – Hayden Schiff
                  Jul 31 '15 at 20:20






                  @davidjb Since synchronous requests are considered deprecated now, an alternative solution might be to redirect the user in the callback of the async request.
                  – Hayden Schiff
                  Jul 31 '15 at 20:20






                  1




                  1




                  David: chrome now permits this for XHRs, and I can confirm that it is still working in chrome canary. bugs.chromium.org/p/chromium/issues/detail?id=435547
                  – CpnCrunch
                  May 25 '17 at 17:49




                  David: chrome now permits this for XHRs, and I can confirm that it is still working in chrome canary. bugs.chromium.org/p/chromium/issues/detail?id=435547
                  – CpnCrunch
                  May 25 '17 at 17:49










                  up vote
                  168
                  down vote













                  Have the user click on a link to https://log:out@example.com/. That will overwrite existing credentials with invalid ones; logging them out.






                  share|improve this answer



















                  • 17




                    Why does this one not get more upvotes? Seems like a simple and working solution to me. Are there any known problems with this approach?
                    – amoebe
                    Jan 17 '14 at 14:00






                  • 24




                    This would no longer work in Chrome, which for security reasons ignores credentials in a URL.
                    – Thom
                    Jun 6 '14 at 9:49






                  • 5




                    This Worked for me :) I am using Chrome Version 32.0.1700.102
                    – abottoni
                    Aug 6 '14 at 13:28






                  • 5




                    problem: using version 39.0 of chrome, When I click the logout link via this method, Chrome remembers the bad login credentials, and prompts for new login credentials on every page load, until I go to example.com without any specified login credentials, to clear chrome's memory.
                    – Scott
                    Jan 23 '15 at 4:08






                  • 4




                    Hi, I cannot use it for https on Chrome.
                    – thienkhoi tran
                    Aug 28 '15 at 9:51















                  up vote
                  168
                  down vote













                  Have the user click on a link to https://log:out@example.com/. That will overwrite existing credentials with invalid ones; logging them out.






                  share|improve this answer



















                  • 17




                    Why does this one not get more upvotes? Seems like a simple and working solution to me. Are there any known problems with this approach?
                    – amoebe
                    Jan 17 '14 at 14:00






                  • 24




                    This would no longer work in Chrome, which for security reasons ignores credentials in a URL.
                    – Thom
                    Jun 6 '14 at 9:49






                  • 5




                    This Worked for me :) I am using Chrome Version 32.0.1700.102
                    – abottoni
                    Aug 6 '14 at 13:28






                  • 5




                    problem: using version 39.0 of chrome, When I click the logout link via this method, Chrome remembers the bad login credentials, and prompts for new login credentials on every page load, until I go to example.com without any specified login credentials, to clear chrome's memory.
                    – Scott
                    Jan 23 '15 at 4:08






                  • 4




                    Hi, I cannot use it for https on Chrome.
                    – thienkhoi tran
                    Aug 28 '15 at 9:51













                  up vote
                  168
                  down vote










                  up vote
                  168
                  down vote









                  Have the user click on a link to https://log:out@example.com/. That will overwrite existing credentials with invalid ones; logging them out.






                  share|improve this answer














                  Have the user click on a link to https://log:out@example.com/. That will overwrite existing credentials with invalid ones; logging them out.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Sep 16 '14 at 11:13









                  Bergi

                  360k56535855




                  360k56535855










                  answered Oct 8 '13 at 21:28









                  Matthew Welborn

                  1,697172




                  1,697172








                  • 17




                    Why does this one not get more upvotes? Seems like a simple and working solution to me. Are there any known problems with this approach?
                    – amoebe
                    Jan 17 '14 at 14:00






                  • 24




                    This would no longer work in Chrome, which for security reasons ignores credentials in a URL.
                    – Thom
                    Jun 6 '14 at 9:49






                  • 5




                    This Worked for me :) I am using Chrome Version 32.0.1700.102
                    – abottoni
                    Aug 6 '14 at 13:28






                  • 5




                    problem: using version 39.0 of chrome, When I click the logout link via this method, Chrome remembers the bad login credentials, and prompts for new login credentials on every page load, until I go to example.com without any specified login credentials, to clear chrome's memory.
                    – Scott
                    Jan 23 '15 at 4:08






                  • 4




                    Hi, I cannot use it for https on Chrome.
                    – thienkhoi tran
                    Aug 28 '15 at 9:51














                  • 17




                    Why does this one not get more upvotes? Seems like a simple and working solution to me. Are there any known problems with this approach?
                    – amoebe
                    Jan 17 '14 at 14:00






                  • 24




                    This would no longer work in Chrome, which for security reasons ignores credentials in a URL.
                    – Thom
                    Jun 6 '14 at 9:49






                  • 5




                    This Worked for me :) I am using Chrome Version 32.0.1700.102
                    – abottoni
                    Aug 6 '14 at 13:28






                  • 5




                    problem: using version 39.0 of chrome, When I click the logout link via this method, Chrome remembers the bad login credentials, and prompts for new login credentials on every page load, until I go to example.com without any specified login credentials, to clear chrome's memory.
                    – Scott
                    Jan 23 '15 at 4:08






                  • 4




                    Hi, I cannot use it for https on Chrome.
                    – thienkhoi tran
                    Aug 28 '15 at 9:51








                  17




                  17




                  Why does this one not get more upvotes? Seems like a simple and working solution to me. Are there any known problems with this approach?
                  – amoebe
                  Jan 17 '14 at 14:00




                  Why does this one not get more upvotes? Seems like a simple and working solution to me. Are there any known problems with this approach?
                  – amoebe
                  Jan 17 '14 at 14:00




                  24




                  24




                  This would no longer work in Chrome, which for security reasons ignores credentials in a URL.
                  – Thom
                  Jun 6 '14 at 9:49




                  This would no longer work in Chrome, which for security reasons ignores credentials in a URL.
                  – Thom
                  Jun 6 '14 at 9:49




                  5




                  5




                  This Worked for me :) I am using Chrome Version 32.0.1700.102
                  – abottoni
                  Aug 6 '14 at 13:28




                  This Worked for me :) I am using Chrome Version 32.0.1700.102
                  – abottoni
                  Aug 6 '14 at 13:28




                  5




                  5




                  problem: using version 39.0 of chrome, When I click the logout link via this method, Chrome remembers the bad login credentials, and prompts for new login credentials on every page load, until I go to example.com without any specified login credentials, to clear chrome's memory.
                  – Scott
                  Jan 23 '15 at 4:08




                  problem: using version 39.0 of chrome, When I click the logout link via this method, Chrome remembers the bad login credentials, and prompts for new login credentials on every page load, until I go to example.com without any specified login credentials, to clear chrome's memory.
                  – Scott
                  Jan 23 '15 at 4:08




                  4




                  4




                  Hi, I cannot use it for https on Chrome.
                  – thienkhoi tran
                  Aug 28 '15 at 9:51




                  Hi, I cannot use it for https on Chrome.
                  – thienkhoi tran
                  Aug 28 '15 at 9:51










                  up vote
                  57
                  down vote













                  You can do it entirely in JavaScript:



                  IE has (for a long time) standard API for clearing Basic Authentication cache:



                  document.execCommand("ClearAuthenticationCache")


                  Should return true when it works. Returns either false, undefined or blows up on other browsers.



                  New browsers (as of Dec 2012: Chrome, FireFox, Safari) have "magic" behavior. If they see a successful basic auth request with any bogus other username (let's say logout) they clear the credentials cache and possibly set it for that new bogus user name, which you need to make sure is not a valid user name for viewing content.



                  Basic example of that is:



                  var p = window.location.protocol + '//'
                  // current location must return 200 OK for this GET
                  window.location = window.location.href.replace(p, p + 'logout:password@')


                  An "asynchronous" way of doing the above is to do an AJAX call utilizing the logout username. Example:



                  (function(safeLocation){
                  var outcome, u, m = "You should be logged out now.";
                  // IE has a simple solution for it - API:
                  try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
                  // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
                  if (!outcome) {
                  // Let's create an xmlhttp object
                  outcome = (function(x){
                  if (x) {
                  // the reason we use "random" value for password is
                  // that browsers cache requests. changing
                  // password effectively behaves like cache-busing.
                  x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                  x.send("")
                  // x.abort()
                  return 1 // this is **speculative** "We are done."
                  } else {
                  return
                  }
                  })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
                  }
                  if (!outcome) {
                  m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
                  }
                  alert(m)
                  // return !!outcome
                  })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)


                  You can make it a bookmarklet too:



                  javascript:(function(c){var a,b="You should be logged out now.";try{a=document.execCommand("ClearAuthenticationCache")}catch(d){}a||((a=window.XMLHttpRequest?new window.XMLHttpRequest:window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):void 0)?(a.open("HEAD",c||location.href,!0,"logout",(new Date).getTime().toString()),a.send(""),a=1):a=void 0);a||(b="Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.");alert(b)})(/*pass safeLocation here if you need*/);






                  share|improve this answer



















                  • 1




                    Does this require special server-side handling of the logout username and/or logout URL?
                    – ulidtko
                    Oct 7 '13 at 19:30






                  • 1




                    @ulidtko No, it shouldn't - all handling is client-side. The only situation that would need special handling is if a user called logout happens to exist and happens to have the generated password. In that almost impossibly-rare case, change the user ID to one that won't exist in your system.
                    – davidjb
                    Mar 20 '14 at 5:58






                  • 1




                    I used the bookmarklet above today and I works well.
                    – David Gleba
                    May 13 '15 at 12:51










                  • I used this and it worked for Chrome and FF. I only had to do an extra "GET" on my logout.php page to clear the $_SESSION.
                    – urban
                    Oct 9 '15 at 10:08










                  • The bookmarklet works on Edge, too. Simply use with <a href='javascript:......need*/);'>Logout</a>
                    – Eric
                    Nov 30 '15 at 6:57

















                  up vote
                  57
                  down vote













                  You can do it entirely in JavaScript:



                  IE has (for a long time) standard API for clearing Basic Authentication cache:



                  document.execCommand("ClearAuthenticationCache")


                  Should return true when it works. Returns either false, undefined or blows up on other browsers.



                  New browsers (as of Dec 2012: Chrome, FireFox, Safari) have "magic" behavior. If they see a successful basic auth request with any bogus other username (let's say logout) they clear the credentials cache and possibly set it for that new bogus user name, which you need to make sure is not a valid user name for viewing content.



                  Basic example of that is:



                  var p = window.location.protocol + '//'
                  // current location must return 200 OK for this GET
                  window.location = window.location.href.replace(p, p + 'logout:password@')


                  An "asynchronous" way of doing the above is to do an AJAX call utilizing the logout username. Example:



                  (function(safeLocation){
                  var outcome, u, m = "You should be logged out now.";
                  // IE has a simple solution for it - API:
                  try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
                  // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
                  if (!outcome) {
                  // Let's create an xmlhttp object
                  outcome = (function(x){
                  if (x) {
                  // the reason we use "random" value for password is
                  // that browsers cache requests. changing
                  // password effectively behaves like cache-busing.
                  x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                  x.send("")
                  // x.abort()
                  return 1 // this is **speculative** "We are done."
                  } else {
                  return
                  }
                  })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
                  }
                  if (!outcome) {
                  m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
                  }
                  alert(m)
                  // return !!outcome
                  })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)


                  You can make it a bookmarklet too:



                  javascript:(function(c){var a,b="You should be logged out now.";try{a=document.execCommand("ClearAuthenticationCache")}catch(d){}a||((a=window.XMLHttpRequest?new window.XMLHttpRequest:window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):void 0)?(a.open("HEAD",c||location.href,!0,"logout",(new Date).getTime().toString()),a.send(""),a=1):a=void 0);a||(b="Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.");alert(b)})(/*pass safeLocation here if you need*/);






                  share|improve this answer



















                  • 1




                    Does this require special server-side handling of the logout username and/or logout URL?
                    – ulidtko
                    Oct 7 '13 at 19:30






                  • 1




                    @ulidtko No, it shouldn't - all handling is client-side. The only situation that would need special handling is if a user called logout happens to exist and happens to have the generated password. In that almost impossibly-rare case, change the user ID to one that won't exist in your system.
                    – davidjb
                    Mar 20 '14 at 5:58






                  • 1




                    I used the bookmarklet above today and I works well.
                    – David Gleba
                    May 13 '15 at 12:51










                  • I used this and it worked for Chrome and FF. I only had to do an extra "GET" on my logout.php page to clear the $_SESSION.
                    – urban
                    Oct 9 '15 at 10:08










                  • The bookmarklet works on Edge, too. Simply use with <a href='javascript:......need*/);'>Logout</a>
                    – Eric
                    Nov 30 '15 at 6:57















                  up vote
                  57
                  down vote










                  up vote
                  57
                  down vote









                  You can do it entirely in JavaScript:



                  IE has (for a long time) standard API for clearing Basic Authentication cache:



                  document.execCommand("ClearAuthenticationCache")


                  Should return true when it works. Returns either false, undefined or blows up on other browsers.



                  New browsers (as of Dec 2012: Chrome, FireFox, Safari) have "magic" behavior. If they see a successful basic auth request with any bogus other username (let's say logout) they clear the credentials cache and possibly set it for that new bogus user name, which you need to make sure is not a valid user name for viewing content.



                  Basic example of that is:



                  var p = window.location.protocol + '//'
                  // current location must return 200 OK for this GET
                  window.location = window.location.href.replace(p, p + 'logout:password@')


                  An "asynchronous" way of doing the above is to do an AJAX call utilizing the logout username. Example:



                  (function(safeLocation){
                  var outcome, u, m = "You should be logged out now.";
                  // IE has a simple solution for it - API:
                  try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
                  // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
                  if (!outcome) {
                  // Let's create an xmlhttp object
                  outcome = (function(x){
                  if (x) {
                  // the reason we use "random" value for password is
                  // that browsers cache requests. changing
                  // password effectively behaves like cache-busing.
                  x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                  x.send("")
                  // x.abort()
                  return 1 // this is **speculative** "We are done."
                  } else {
                  return
                  }
                  })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
                  }
                  if (!outcome) {
                  m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
                  }
                  alert(m)
                  // return !!outcome
                  })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)


                  You can make it a bookmarklet too:



                  javascript:(function(c){var a,b="You should be logged out now.";try{a=document.execCommand("ClearAuthenticationCache")}catch(d){}a||((a=window.XMLHttpRequest?new window.XMLHttpRequest:window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):void 0)?(a.open("HEAD",c||location.href,!0,"logout",(new Date).getTime().toString()),a.send(""),a=1):a=void 0);a||(b="Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.");alert(b)})(/*pass safeLocation here if you need*/);






                  share|improve this answer














                  You can do it entirely in JavaScript:



                  IE has (for a long time) standard API for clearing Basic Authentication cache:



                  document.execCommand("ClearAuthenticationCache")


                  Should return true when it works. Returns either false, undefined or blows up on other browsers.



                  New browsers (as of Dec 2012: Chrome, FireFox, Safari) have "magic" behavior. If they see a successful basic auth request with any bogus other username (let's say logout) they clear the credentials cache and possibly set it for that new bogus user name, which you need to make sure is not a valid user name for viewing content.



                  Basic example of that is:



                  var p = window.location.protocol + '//'
                  // current location must return 200 OK for this GET
                  window.location = window.location.href.replace(p, p + 'logout:password@')


                  An "asynchronous" way of doing the above is to do an AJAX call utilizing the logout username. Example:



                  (function(safeLocation){
                  var outcome, u, m = "You should be logged out now.";
                  // IE has a simple solution for it - API:
                  try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
                  // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
                  if (!outcome) {
                  // Let's create an xmlhttp object
                  outcome = (function(x){
                  if (x) {
                  // the reason we use "random" value for password is
                  // that browsers cache requests. changing
                  // password effectively behaves like cache-busing.
                  x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                  x.send("")
                  // x.abort()
                  return 1 // this is **speculative** "We are done."
                  } else {
                  return
                  }
                  })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
                  }
                  if (!outcome) {
                  m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
                  }
                  alert(m)
                  // return !!outcome
                  })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)


                  You can make it a bookmarklet too:



                  javascript:(function(c){var a,b="You should be logged out now.";try{a=document.execCommand("ClearAuthenticationCache")}catch(d){}a||((a=window.XMLHttpRequest?new window.XMLHttpRequest:window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):void 0)?(a.open("HEAD",c||location.href,!0,"logout",(new Date).getTime().toString()),a.send(""),a=1):a=void 0);a||(b="Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser.");alert(b)})(/*pass safeLocation here if you need*/);







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 1 '13 at 1:01

























                  answered Jan 15 '13 at 1:46









                  ddotsenko

                  4,0811821




                  4,0811821








                  • 1




                    Does this require special server-side handling of the logout username and/or logout URL?
                    – ulidtko
                    Oct 7 '13 at 19:30






                  • 1




                    @ulidtko No, it shouldn't - all handling is client-side. The only situation that would need special handling is if a user called logout happens to exist and happens to have the generated password. In that almost impossibly-rare case, change the user ID to one that won't exist in your system.
                    – davidjb
                    Mar 20 '14 at 5:58






                  • 1




                    I used the bookmarklet above today and I works well.
                    – David Gleba
                    May 13 '15 at 12:51










                  • I used this and it worked for Chrome and FF. I only had to do an extra "GET" on my logout.php page to clear the $_SESSION.
                    – urban
                    Oct 9 '15 at 10:08










                  • The bookmarklet works on Edge, too. Simply use with <a href='javascript:......need*/);'>Logout</a>
                    – Eric
                    Nov 30 '15 at 6:57
















                  • 1




                    Does this require special server-side handling of the logout username and/or logout URL?
                    – ulidtko
                    Oct 7 '13 at 19:30






                  • 1




                    @ulidtko No, it shouldn't - all handling is client-side. The only situation that would need special handling is if a user called logout happens to exist and happens to have the generated password. In that almost impossibly-rare case, change the user ID to one that won't exist in your system.
                    – davidjb
                    Mar 20 '14 at 5:58






                  • 1




                    I used the bookmarklet above today and I works well.
                    – David Gleba
                    May 13 '15 at 12:51










                  • I used this and it worked for Chrome and FF. I only had to do an extra "GET" on my logout.php page to clear the $_SESSION.
                    – urban
                    Oct 9 '15 at 10:08










                  • The bookmarklet works on Edge, too. Simply use with <a href='javascript:......need*/);'>Logout</a>
                    – Eric
                    Nov 30 '15 at 6:57










                  1




                  1




                  Does this require special server-side handling of the logout username and/or logout URL?
                  – ulidtko
                  Oct 7 '13 at 19:30




                  Does this require special server-side handling of the logout username and/or logout URL?
                  – ulidtko
                  Oct 7 '13 at 19:30




                  1




                  1




                  @ulidtko No, it shouldn't - all handling is client-side. The only situation that would need special handling is if a user called logout happens to exist and happens to have the generated password. In that almost impossibly-rare case, change the user ID to one that won't exist in your system.
                  – davidjb
                  Mar 20 '14 at 5:58




                  @ulidtko No, it shouldn't - all handling is client-side. The only situation that would need special handling is if a user called logout happens to exist and happens to have the generated password. In that almost impossibly-rare case, change the user ID to one that won't exist in your system.
                  – davidjb
                  Mar 20 '14 at 5:58




                  1




                  1




                  I used the bookmarklet above today and I works well.
                  – David Gleba
                  May 13 '15 at 12:51




                  I used the bookmarklet above today and I works well.
                  – David Gleba
                  May 13 '15 at 12:51












                  I used this and it worked for Chrome and FF. I only had to do an extra "GET" on my logout.php page to clear the $_SESSION.
                  – urban
                  Oct 9 '15 at 10:08




                  I used this and it worked for Chrome and FF. I only had to do an extra "GET" on my logout.php page to clear the $_SESSION.
                  – urban
                  Oct 9 '15 at 10:08












                  The bookmarklet works on Edge, too. Simply use with <a href='javascript:......need*/);'>Logout</a>
                  – Eric
                  Nov 30 '15 at 6:57






                  The bookmarklet works on Edge, too. Simply use with <a href='javascript:......need*/);'>Logout</a>
                  – Eric
                  Nov 30 '15 at 6:57












                  up vote
                  14
                  down vote













                  The following function is confirmed working for Firefox 40, Chrome 44, Opera 31 and IE 11.
                  Bowser is used for browser detection, jQuery is also used.


                  - secUrl is the url to a password protected area from which to log out.

                  - redirUrl is the url to a non password protected area (logout success page).


                  - you might wish to increase the redirect timer (currently 200ms).






                  function logout(secUrl, redirUrl) {
                  if (bowser.msie) {
                  document.execCommand('ClearAuthenticationCache', 'false');
                  } else if (bowser.gecko) {
                  $.ajax({
                  async: false,
                  url: secUrl,
                  type: 'GET',
                  username: 'logout'
                  });
                  } else if (bowser.webkit) {
                  var xmlhttp = new XMLHttpRequest();
                  xmlhttp.open("GET", secUrl, true);
                  xmlhttp.setRequestHeader("Authorization", "Basic logout");
                  xmlhttp.send();
                  } else {
                  alert("Logging out automatically is unsupported for " + bowser.name
                  + "nYou must close the browser to log out.");
                  }
                  setTimeout(function () {
                  window.location.href = redirUrl;
                  }, 200);
                  }








                  share|improve this answer





















                  • this is the most comprehensive answer
                    – belidzs
                    Oct 21 '15 at 14:51










                  • Is there any reason for the $.ajax variant being synchronous (async: false) and the xmlhttp variant being asynchronous (the true in open())?
                    – Bowi
                    Sep 14 '17 at 13:34










                  • Chrome now uses the rendering engine Blink, so you have to change (bowser.gecko) to (bowser.gecko || bowser.blink).
                    – Bowi
                    Sep 15 '17 at 14:10






                  • 1




                    Why does gecko/blink use $.ajax and webkit use new XMLHttpRequest? Shouldn't gecko/blink be able to do XMLHttpRequest and webkit be able to do $.ajax too? I'm confused.
                    – RemyNL
                    Oct 31 at 12:13















                  up vote
                  14
                  down vote













                  The following function is confirmed working for Firefox 40, Chrome 44, Opera 31 and IE 11.
                  Bowser is used for browser detection, jQuery is also used.


                  - secUrl is the url to a password protected area from which to log out.

                  - redirUrl is the url to a non password protected area (logout success page).


                  - you might wish to increase the redirect timer (currently 200ms).






                  function logout(secUrl, redirUrl) {
                  if (bowser.msie) {
                  document.execCommand('ClearAuthenticationCache', 'false');
                  } else if (bowser.gecko) {
                  $.ajax({
                  async: false,
                  url: secUrl,
                  type: 'GET',
                  username: 'logout'
                  });
                  } else if (bowser.webkit) {
                  var xmlhttp = new XMLHttpRequest();
                  xmlhttp.open("GET", secUrl, true);
                  xmlhttp.setRequestHeader("Authorization", "Basic logout");
                  xmlhttp.send();
                  } else {
                  alert("Logging out automatically is unsupported for " + bowser.name
                  + "nYou must close the browser to log out.");
                  }
                  setTimeout(function () {
                  window.location.href = redirUrl;
                  }, 200);
                  }








                  share|improve this answer





















                  • this is the most comprehensive answer
                    – belidzs
                    Oct 21 '15 at 14:51










                  • Is there any reason for the $.ajax variant being synchronous (async: false) and the xmlhttp variant being asynchronous (the true in open())?
                    – Bowi
                    Sep 14 '17 at 13:34










                  • Chrome now uses the rendering engine Blink, so you have to change (bowser.gecko) to (bowser.gecko || bowser.blink).
                    – Bowi
                    Sep 15 '17 at 14:10






                  • 1




                    Why does gecko/blink use $.ajax and webkit use new XMLHttpRequest? Shouldn't gecko/blink be able to do XMLHttpRequest and webkit be able to do $.ajax too? I'm confused.
                    – RemyNL
                    Oct 31 at 12:13













                  up vote
                  14
                  down vote










                  up vote
                  14
                  down vote









                  The following function is confirmed working for Firefox 40, Chrome 44, Opera 31 and IE 11.
                  Bowser is used for browser detection, jQuery is also used.


                  - secUrl is the url to a password protected area from which to log out.

                  - redirUrl is the url to a non password protected area (logout success page).


                  - you might wish to increase the redirect timer (currently 200ms).






                  function logout(secUrl, redirUrl) {
                  if (bowser.msie) {
                  document.execCommand('ClearAuthenticationCache', 'false');
                  } else if (bowser.gecko) {
                  $.ajax({
                  async: false,
                  url: secUrl,
                  type: 'GET',
                  username: 'logout'
                  });
                  } else if (bowser.webkit) {
                  var xmlhttp = new XMLHttpRequest();
                  xmlhttp.open("GET", secUrl, true);
                  xmlhttp.setRequestHeader("Authorization", "Basic logout");
                  xmlhttp.send();
                  } else {
                  alert("Logging out automatically is unsupported for " + bowser.name
                  + "nYou must close the browser to log out.");
                  }
                  setTimeout(function () {
                  window.location.href = redirUrl;
                  }, 200);
                  }








                  share|improve this answer












                  The following function is confirmed working for Firefox 40, Chrome 44, Opera 31 and IE 11.
                  Bowser is used for browser detection, jQuery is also used.


                  - secUrl is the url to a password protected area from which to log out.

                  - redirUrl is the url to a non password protected area (logout success page).


                  - you might wish to increase the redirect timer (currently 200ms).






                  function logout(secUrl, redirUrl) {
                  if (bowser.msie) {
                  document.execCommand('ClearAuthenticationCache', 'false');
                  } else if (bowser.gecko) {
                  $.ajax({
                  async: false,
                  url: secUrl,
                  type: 'GET',
                  username: 'logout'
                  });
                  } else if (bowser.webkit) {
                  var xmlhttp = new XMLHttpRequest();
                  xmlhttp.open("GET", secUrl, true);
                  xmlhttp.setRequestHeader("Authorization", "Basic logout");
                  xmlhttp.send();
                  } else {
                  alert("Logging out automatically is unsupported for " + bowser.name
                  + "nYou must close the browser to log out.");
                  }
                  setTimeout(function () {
                  window.location.href = redirUrl;
                  }, 200);
                  }








                  function logout(secUrl, redirUrl) {
                  if (bowser.msie) {
                  document.execCommand('ClearAuthenticationCache', 'false');
                  } else if (bowser.gecko) {
                  $.ajax({
                  async: false,
                  url: secUrl,
                  type: 'GET',
                  username: 'logout'
                  });
                  } else if (bowser.webkit) {
                  var xmlhttp = new XMLHttpRequest();
                  xmlhttp.open("GET", secUrl, true);
                  xmlhttp.setRequestHeader("Authorization", "Basic logout");
                  xmlhttp.send();
                  } else {
                  alert("Logging out automatically is unsupported for " + bowser.name
                  + "nYou must close the browser to log out.");
                  }
                  setTimeout(function () {
                  window.location.href = redirUrl;
                  }, 200);
                  }





                  function logout(secUrl, redirUrl) {
                  if (bowser.msie) {
                  document.execCommand('ClearAuthenticationCache', 'false');
                  } else if (bowser.gecko) {
                  $.ajax({
                  async: false,
                  url: secUrl,
                  type: 'GET',
                  username: 'logout'
                  });
                  } else if (bowser.webkit) {
                  var xmlhttp = new XMLHttpRequest();
                  xmlhttp.open("GET", secUrl, true);
                  xmlhttp.setRequestHeader("Authorization", "Basic logout");
                  xmlhttp.send();
                  } else {
                  alert("Logging out automatically is unsupported for " + bowser.name
                  + "nYou must close the browser to log out.");
                  }
                  setTimeout(function () {
                  window.location.href = redirUrl;
                  }, 200);
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 1 '15 at 7:24









                  mthoring

                  14112




                  14112












                  • this is the most comprehensive answer
                    – belidzs
                    Oct 21 '15 at 14:51










                  • Is there any reason for the $.ajax variant being synchronous (async: false) and the xmlhttp variant being asynchronous (the true in open())?
                    – Bowi
                    Sep 14 '17 at 13:34










                  • Chrome now uses the rendering engine Blink, so you have to change (bowser.gecko) to (bowser.gecko || bowser.blink).
                    – Bowi
                    Sep 15 '17 at 14:10






                  • 1




                    Why does gecko/blink use $.ajax and webkit use new XMLHttpRequest? Shouldn't gecko/blink be able to do XMLHttpRequest and webkit be able to do $.ajax too? I'm confused.
                    – RemyNL
                    Oct 31 at 12:13


















                  • this is the most comprehensive answer
                    – belidzs
                    Oct 21 '15 at 14:51










                  • Is there any reason for the $.ajax variant being synchronous (async: false) and the xmlhttp variant being asynchronous (the true in open())?
                    – Bowi
                    Sep 14 '17 at 13:34










                  • Chrome now uses the rendering engine Blink, so you have to change (bowser.gecko) to (bowser.gecko || bowser.blink).
                    – Bowi
                    Sep 15 '17 at 14:10






                  • 1




                    Why does gecko/blink use $.ajax and webkit use new XMLHttpRequest? Shouldn't gecko/blink be able to do XMLHttpRequest and webkit be able to do $.ajax too? I'm confused.
                    – RemyNL
                    Oct 31 at 12:13
















                  this is the most comprehensive answer
                  – belidzs
                  Oct 21 '15 at 14:51




                  this is the most comprehensive answer
                  – belidzs
                  Oct 21 '15 at 14:51












                  Is there any reason for the $.ajax variant being synchronous (async: false) and the xmlhttp variant being asynchronous (the true in open())?
                  – Bowi
                  Sep 14 '17 at 13:34




                  Is there any reason for the $.ajax variant being synchronous (async: false) and the xmlhttp variant being asynchronous (the true in open())?
                  – Bowi
                  Sep 14 '17 at 13:34












                  Chrome now uses the rendering engine Blink, so you have to change (bowser.gecko) to (bowser.gecko || bowser.blink).
                  – Bowi
                  Sep 15 '17 at 14:10




                  Chrome now uses the rendering engine Blink, so you have to change (bowser.gecko) to (bowser.gecko || bowser.blink).
                  – Bowi
                  Sep 15 '17 at 14:10




                  1




                  1




                  Why does gecko/blink use $.ajax and webkit use new XMLHttpRequest? Shouldn't gecko/blink be able to do XMLHttpRequest and webkit be able to do $.ajax too? I'm confused.
                  – RemyNL
                  Oct 31 at 12:13




                  Why does gecko/blink use $.ajax and webkit use new XMLHttpRequest? Shouldn't gecko/blink be able to do XMLHttpRequest and webkit be able to do $.ajax too? I'm confused.
                  – RemyNL
                  Oct 31 at 12:13










                  up vote
                  10
                  down vote













                  This isn't directly possible with Basic-Authentication.



                  There's no mechanism in the HTTP specification for the server to tell the browser to stop sending the credentials that the user already presented.



                  There are "hacks" (see other answers) typically involving using XMLHttpRequest to send an HTTP request with incorrect credentials to overwrite the ones originally supplied.






                  share|improve this answer



















                  • 11




                    In Theory. Practice proves otherwise as can be seen from the other answers.
                    – Stijn de Witt
                    Apr 1 '14 at 11:14






                  • 2




                    And as you can also see from the other answers, not in a reliable, consistent and fail-safe way !
                    – jplandrain
                    Aug 21 '17 at 9:55















                  up vote
                  10
                  down vote













                  This isn't directly possible with Basic-Authentication.



                  There's no mechanism in the HTTP specification for the server to tell the browser to stop sending the credentials that the user already presented.



                  There are "hacks" (see other answers) typically involving using XMLHttpRequest to send an HTTP request with incorrect credentials to overwrite the ones originally supplied.






                  share|improve this answer



















                  • 11




                    In Theory. Practice proves otherwise as can be seen from the other answers.
                    – Stijn de Witt
                    Apr 1 '14 at 11:14






                  • 2




                    And as you can also see from the other answers, not in a reliable, consistent and fail-safe way !
                    – jplandrain
                    Aug 21 '17 at 9:55













                  up vote
                  10
                  down vote










                  up vote
                  10
                  down vote









                  This isn't directly possible with Basic-Authentication.



                  There's no mechanism in the HTTP specification for the server to tell the browser to stop sending the credentials that the user already presented.



                  There are "hacks" (see other answers) typically involving using XMLHttpRequest to send an HTTP request with incorrect credentials to overwrite the ones originally supplied.






                  share|improve this answer














                  This isn't directly possible with Basic-Authentication.



                  There's no mechanism in the HTTP specification for the server to tell the browser to stop sending the credentials that the user already presented.



                  There are "hacks" (see other answers) typically involving using XMLHttpRequest to send an HTTP request with incorrect credentials to overwrite the ones originally supplied.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 9 '15 at 10:25

























                  answered Oct 24 '08 at 13:30









                  Alnitak

                  268k62336426




                  268k62336426








                  • 11




                    In Theory. Practice proves otherwise as can be seen from the other answers.
                    – Stijn de Witt
                    Apr 1 '14 at 11:14






                  • 2




                    And as you can also see from the other answers, not in a reliable, consistent and fail-safe way !
                    – jplandrain
                    Aug 21 '17 at 9:55














                  • 11




                    In Theory. Practice proves otherwise as can be seen from the other answers.
                    – Stijn de Witt
                    Apr 1 '14 at 11:14






                  • 2




                    And as you can also see from the other answers, not in a reliable, consistent and fail-safe way !
                    – jplandrain
                    Aug 21 '17 at 9:55








                  11




                  11




                  In Theory. Practice proves otherwise as can be seen from the other answers.
                  – Stijn de Witt
                  Apr 1 '14 at 11:14




                  In Theory. Practice proves otherwise as can be seen from the other answers.
                  – Stijn de Witt
                  Apr 1 '14 at 11:14




                  2




                  2




                  And as you can also see from the other answers, not in a reliable, consistent and fail-safe way !
                  – jplandrain
                  Aug 21 '17 at 9:55




                  And as you can also see from the other answers, not in a reliable, consistent and fail-safe way !
                  – jplandrain
                  Aug 21 '17 at 9:55










                  up vote
                  9
                  down vote













                  Here's a very simple Javascript example using jQuery:



                  function logout(to_url) {
                  var out = window.location.href.replace(/:///, '://log:out@');

                  jQuery.get(out).error(function() {
                  window.location = to_url;
                  });
                  }


                  This log user out without showing him the browser log-in box again, then redirect him to a logged out page






                  share|improve this answer





















                  • As of jQuery 1.8, the .error() method is deprecated and removed from 3.0 Use .fail() instead.
                    – RemyNL
                    Oct 31 at 11:27















                  up vote
                  9
                  down vote













                  Here's a very simple Javascript example using jQuery:



                  function logout(to_url) {
                  var out = window.location.href.replace(/:///, '://log:out@');

                  jQuery.get(out).error(function() {
                  window.location = to_url;
                  });
                  }


                  This log user out without showing him the browser log-in box again, then redirect him to a logged out page






                  share|improve this answer





















                  • As of jQuery 1.8, the .error() method is deprecated and removed from 3.0 Use .fail() instead.
                    – RemyNL
                    Oct 31 at 11:27













                  up vote
                  9
                  down vote










                  up vote
                  9
                  down vote









                  Here's a very simple Javascript example using jQuery:



                  function logout(to_url) {
                  var out = window.location.href.replace(/:///, '://log:out@');

                  jQuery.get(out).error(function() {
                  window.location = to_url;
                  });
                  }


                  This log user out without showing him the browser log-in box again, then redirect him to a logged out page






                  share|improve this answer












                  Here's a very simple Javascript example using jQuery:



                  function logout(to_url) {
                  var out = window.location.href.replace(/:///, '://log:out@');

                  jQuery.get(out).error(function() {
                  window.location = to_url;
                  });
                  }


                  This log user out without showing him the browser log-in box again, then redirect him to a logged out page







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jun 10 '14 at 12:35









                  Romuald Brunet

                  2,90422526




                  2,90422526












                  • As of jQuery 1.8, the .error() method is deprecated and removed from 3.0 Use .fail() instead.
                    – RemyNL
                    Oct 31 at 11:27


















                  • As of jQuery 1.8, the .error() method is deprecated and removed from 3.0 Use .fail() instead.
                    – RemyNL
                    Oct 31 at 11:27
















                  As of jQuery 1.8, the .error() method is deprecated and removed from 3.0 Use .fail() instead.
                  – RemyNL
                  Oct 31 at 11:27




                  As of jQuery 1.8, the .error() method is deprecated and removed from 3.0 Use .fail() instead.
                  – RemyNL
                  Oct 31 at 11:27










                  up vote
                  6
                  down vote













                  It's actually pretty simple.



                  Just visit the following in your browser and use wrong credentials:
                  http://username:password@yourdomain.com



                  That should "log you out".






                  share|improve this answer





















                  • But the user have to be a REAL user, othervise I got "401 Unauthorized", but using BACK button I am able to continue work as a previously logged user. Tested on Abyss web server X1 (2.11.1)
                    – user2956477
                    Dec 29 '16 at 10:39






                  • 1




                    Duplicate answer (see Matthew Welborn's above).
                    – Skippy le Grand Gourou
                    Sep 12 at 9:53















                  up vote
                  6
                  down vote













                  It's actually pretty simple.



                  Just visit the following in your browser and use wrong credentials:
                  http://username:password@yourdomain.com



                  That should "log you out".






                  share|improve this answer





















                  • But the user have to be a REAL user, othervise I got "401 Unauthorized", but using BACK button I am able to continue work as a previously logged user. Tested on Abyss web server X1 (2.11.1)
                    – user2956477
                    Dec 29 '16 at 10:39






                  • 1




                    Duplicate answer (see Matthew Welborn's above).
                    – Skippy le Grand Gourou
                    Sep 12 at 9:53













                  up vote
                  6
                  down vote










                  up vote
                  6
                  down vote









                  It's actually pretty simple.



                  Just visit the following in your browser and use wrong credentials:
                  http://username:password@yourdomain.com



                  That should "log you out".






                  share|improve this answer












                  It's actually pretty simple.



                  Just visit the following in your browser and use wrong credentials:
                  http://username:password@yourdomain.com



                  That should "log you out".







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Feb 18 '15 at 18:59









                  Chiedo

                  4,10611820




                  4,10611820












                  • But the user have to be a REAL user, othervise I got "401 Unauthorized", but using BACK button I am able to continue work as a previously logged user. Tested on Abyss web server X1 (2.11.1)
                    – user2956477
                    Dec 29 '16 at 10:39






                  • 1




                    Duplicate answer (see Matthew Welborn's above).
                    – Skippy le Grand Gourou
                    Sep 12 at 9:53


















                  • But the user have to be a REAL user, othervise I got "401 Unauthorized", but using BACK button I am able to continue work as a previously logged user. Tested on Abyss web server X1 (2.11.1)
                    – user2956477
                    Dec 29 '16 at 10:39






                  • 1




                    Duplicate answer (see Matthew Welborn's above).
                    – Skippy le Grand Gourou
                    Sep 12 at 9:53
















                  But the user have to be a REAL user, othervise I got "401 Unauthorized", but using BACK button I am able to continue work as a previously logged user. Tested on Abyss web server X1 (2.11.1)
                  – user2956477
                  Dec 29 '16 at 10:39




                  But the user have to be a REAL user, othervise I got "401 Unauthorized", but using BACK button I am able to continue work as a previously logged user. Tested on Abyss web server X1 (2.11.1)
                  – user2956477
                  Dec 29 '16 at 10:39




                  1




                  1




                  Duplicate answer (see Matthew Welborn's above).
                  – Skippy le Grand Gourou
                  Sep 12 at 9:53




                  Duplicate answer (see Matthew Welborn's above).
                  – Skippy le Grand Gourou
                  Sep 12 at 9:53










                  up vote
                  5
                  down vote













                  This is working for IE/Netscape/Chrome :



                        function ClearAuthentication(LogOffPage) 
                  {
                  var IsInternetExplorer = false;

                  try
                  {
                  var agt=navigator.userAgent.toLowerCase();
                  if (agt.indexOf("msie") != -1) { IsInternetExplorer = true; }
                  }
                  catch(e)
                  {
                  IsInternetExplorer = false;
                  };

                  if (IsInternetExplorer)
                  {
                  // Logoff Internet Explorer
                  document.execCommand("ClearAuthenticationCache");
                  window.location = LogOffPage;
                  }
                  else
                  {
                  // Logoff every other browsers
                  $.ajax({
                  username: 'unknown',
                  password: 'WrongPassword',
                  url: './cgi-bin/PrimoCgi',
                  type: 'GET',
                  beforeSend: function(xhr)
                  {
                  xhr.setRequestHeader("Authorization", "Basic AAAAAAAAAAAAAAAAAAA=");
                  },

                  error: function(err)
                  {
                  window.location = LogOffPage;
                  }
                  });
                  }
                  }


                  $(document).ready(function ()
                  {
                  $('#Btn1').click(function ()
                  {
                  // Call Clear Authentication
                  ClearAuthentication("force_logout.html");
                  });
                  });





                  share|improve this answer

























                    up vote
                    5
                    down vote













                    This is working for IE/Netscape/Chrome :



                          function ClearAuthentication(LogOffPage) 
                    {
                    var IsInternetExplorer = false;

                    try
                    {
                    var agt=navigator.userAgent.toLowerCase();
                    if (agt.indexOf("msie") != -1) { IsInternetExplorer = true; }
                    }
                    catch(e)
                    {
                    IsInternetExplorer = false;
                    };

                    if (IsInternetExplorer)
                    {
                    // Logoff Internet Explorer
                    document.execCommand("ClearAuthenticationCache");
                    window.location = LogOffPage;
                    }
                    else
                    {
                    // Logoff every other browsers
                    $.ajax({
                    username: 'unknown',
                    password: 'WrongPassword',
                    url: './cgi-bin/PrimoCgi',
                    type: 'GET',
                    beforeSend: function(xhr)
                    {
                    xhr.setRequestHeader("Authorization", "Basic AAAAAAAAAAAAAAAAAAA=");
                    },

                    error: function(err)
                    {
                    window.location = LogOffPage;
                    }
                    });
                    }
                    }


                    $(document).ready(function ()
                    {
                    $('#Btn1').click(function ()
                    {
                    // Call Clear Authentication
                    ClearAuthentication("force_logout.html");
                    });
                    });





                    share|improve this answer























                      up vote
                      5
                      down vote










                      up vote
                      5
                      down vote









                      This is working for IE/Netscape/Chrome :



                            function ClearAuthentication(LogOffPage) 
                      {
                      var IsInternetExplorer = false;

                      try
                      {
                      var agt=navigator.userAgent.toLowerCase();
                      if (agt.indexOf("msie") != -1) { IsInternetExplorer = true; }
                      }
                      catch(e)
                      {
                      IsInternetExplorer = false;
                      };

                      if (IsInternetExplorer)
                      {
                      // Logoff Internet Explorer
                      document.execCommand("ClearAuthenticationCache");
                      window.location = LogOffPage;
                      }
                      else
                      {
                      // Logoff every other browsers
                      $.ajax({
                      username: 'unknown',
                      password: 'WrongPassword',
                      url: './cgi-bin/PrimoCgi',
                      type: 'GET',
                      beforeSend: function(xhr)
                      {
                      xhr.setRequestHeader("Authorization", "Basic AAAAAAAAAAAAAAAAAAA=");
                      },

                      error: function(err)
                      {
                      window.location = LogOffPage;
                      }
                      });
                      }
                      }


                      $(document).ready(function ()
                      {
                      $('#Btn1').click(function ()
                      {
                      // Call Clear Authentication
                      ClearAuthentication("force_logout.html");
                      });
                      });





                      share|improve this answer












                      This is working for IE/Netscape/Chrome :



                            function ClearAuthentication(LogOffPage) 
                      {
                      var IsInternetExplorer = false;

                      try
                      {
                      var agt=navigator.userAgent.toLowerCase();
                      if (agt.indexOf("msie") != -1) { IsInternetExplorer = true; }
                      }
                      catch(e)
                      {
                      IsInternetExplorer = false;
                      };

                      if (IsInternetExplorer)
                      {
                      // Logoff Internet Explorer
                      document.execCommand("ClearAuthenticationCache");
                      window.location = LogOffPage;
                      }
                      else
                      {
                      // Logoff every other browsers
                      $.ajax({
                      username: 'unknown',
                      password: 'WrongPassword',
                      url: './cgi-bin/PrimoCgi',
                      type: 'GET',
                      beforeSend: function(xhr)
                      {
                      xhr.setRequestHeader("Authorization", "Basic AAAAAAAAAAAAAAAAAAA=");
                      },

                      error: function(err)
                      {
                      window.location = LogOffPage;
                      }
                      });
                      }
                      }


                      $(document).ready(function ()
                      {
                      $('#Btn1').click(function ()
                      {
                      // Call Clear Authentication
                      ClearAuthentication("force_logout.html");
                      });
                      });






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 20 '13 at 8:52









                      Claudio

                      5111




                      5111






















                          up vote
                          2
                          down vote













                          function logout() {
                          var userAgent = navigator.userAgent.toLowerCase();

                          if (userAgent.indexOf("msie") != -1) {
                          document.execCommand("ClearAuthenticationCache", false);
                          }

                          xhr_objectCarte = null;

                          if(window.XMLHttpRequest)
                          xhr_object = new XMLHttpRequest();
                          else if(window.ActiveXObject)
                          xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
                          else
                          alert ("Your browser doesn't support XMLHTTPREQUEST");

                          xhr_object.open ('GET', 'http://yourserver.com/rep/index.php', false, 'username', 'password');
                          xhr_object.send ("");
                          xhr_object = null;

                          document.location = 'http://yourserver.com';
                          return false;
                          }





                          share|improve this answer

























                            up vote
                            2
                            down vote













                            function logout() {
                            var userAgent = navigator.userAgent.toLowerCase();

                            if (userAgent.indexOf("msie") != -1) {
                            document.execCommand("ClearAuthenticationCache", false);
                            }

                            xhr_objectCarte = null;

                            if(window.XMLHttpRequest)
                            xhr_object = new XMLHttpRequest();
                            else if(window.ActiveXObject)
                            xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
                            else
                            alert ("Your browser doesn't support XMLHTTPREQUEST");

                            xhr_object.open ('GET', 'http://yourserver.com/rep/index.php', false, 'username', 'password');
                            xhr_object.send ("");
                            xhr_object = null;

                            document.location = 'http://yourserver.com';
                            return false;
                            }





                            share|improve this answer























                              up vote
                              2
                              down vote










                              up vote
                              2
                              down vote









                              function logout() {
                              var userAgent = navigator.userAgent.toLowerCase();

                              if (userAgent.indexOf("msie") != -1) {
                              document.execCommand("ClearAuthenticationCache", false);
                              }

                              xhr_objectCarte = null;

                              if(window.XMLHttpRequest)
                              xhr_object = new XMLHttpRequest();
                              else if(window.ActiveXObject)
                              xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
                              else
                              alert ("Your browser doesn't support XMLHTTPREQUEST");

                              xhr_object.open ('GET', 'http://yourserver.com/rep/index.php', false, 'username', 'password');
                              xhr_object.send ("");
                              xhr_object = null;

                              document.location = 'http://yourserver.com';
                              return false;
                              }





                              share|improve this answer












                              function logout() {
                              var userAgent = navigator.userAgent.toLowerCase();

                              if (userAgent.indexOf("msie") != -1) {
                              document.execCommand("ClearAuthenticationCache", false);
                              }

                              xhr_objectCarte = null;

                              if(window.XMLHttpRequest)
                              xhr_object = new XMLHttpRequest();
                              else if(window.ActiveXObject)
                              xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
                              else
                              alert ("Your browser doesn't support XMLHTTPREQUEST");

                              xhr_object.open ('GET', 'http://yourserver.com/rep/index.php', false, 'username', 'password');
                              xhr_object.send ("");
                              xhr_object = null;

                              document.location = 'http://yourserver.com';
                              return false;
                              }






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Feb 6 '15 at 15:37









                              Charlie

                              212




                              212






















                                  up vote
                                  2
                                  down vote













                                   function logout(url){
                                  var str = url.replace("http://", "http://" + new Date().getTime() + "@");
                                  var xmlhttp;
                                  if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
                                  else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                                  xmlhttp.onreadystatechange=function()
                                  {
                                  if (xmlhttp.readyState==4) location.reload();
                                  }
                                  xmlhttp.open("GET",str,true);
                                  xmlhttp.setRequestHeader("Authorization","Basic xxxxxxxxxx")
                                  xmlhttp.send();
                                  return false;
                                  }





                                  share|improve this answer

























                                    up vote
                                    2
                                    down vote













                                     function logout(url){
                                    var str = url.replace("http://", "http://" + new Date().getTime() + "@");
                                    var xmlhttp;
                                    if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
                                    else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                                    xmlhttp.onreadystatechange=function()
                                    {
                                    if (xmlhttp.readyState==4) location.reload();
                                    }
                                    xmlhttp.open("GET",str,true);
                                    xmlhttp.setRequestHeader("Authorization","Basic xxxxxxxxxx")
                                    xmlhttp.send();
                                    return false;
                                    }





                                    share|improve this answer























                                      up vote
                                      2
                                      down vote










                                      up vote
                                      2
                                      down vote









                                       function logout(url){
                                      var str = url.replace("http://", "http://" + new Date().getTime() + "@");
                                      var xmlhttp;
                                      if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
                                      else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                                      xmlhttp.onreadystatechange=function()
                                      {
                                      if (xmlhttp.readyState==4) location.reload();
                                      }
                                      xmlhttp.open("GET",str,true);
                                      xmlhttp.setRequestHeader("Authorization","Basic xxxxxxxxxx")
                                      xmlhttp.send();
                                      return false;
                                      }





                                      share|improve this answer












                                       function logout(url){
                                      var str = url.replace("http://", "http://" + new Date().getTime() + "@");
                                      var xmlhttp;
                                      if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
                                      else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                                      xmlhttp.onreadystatechange=function()
                                      {
                                      if (xmlhttp.readyState==4) location.reload();
                                      }
                                      xmlhttp.open("GET",str,true);
                                      xmlhttp.setRequestHeader("Authorization","Basic xxxxxxxxxx")
                                      xmlhttp.send();
                                      return false;
                                      }






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Mar 13 '15 at 16:50









                                      Sushovan Mukherjee

                                      354312




                                      354312






















                                          up vote
                                          1
                                          down vote













                                          add this to your application :



                                          @app.route('/logout')
                                          def logout():
                                          return ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'})





                                          share|improve this answer





















                                          • better to use this return : return('Logout', 401)
                                            – Amir Mofakhar
                                            Sep 18 '15 at 13:35















                                          up vote
                                          1
                                          down vote













                                          add this to your application :



                                          @app.route('/logout')
                                          def logout():
                                          return ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'})





                                          share|improve this answer





















                                          • better to use this return : return('Logout', 401)
                                            – Amir Mofakhar
                                            Sep 18 '15 at 13:35













                                          up vote
                                          1
                                          down vote










                                          up vote
                                          1
                                          down vote









                                          add this to your application :



                                          @app.route('/logout')
                                          def logout():
                                          return ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'})





                                          share|improve this answer












                                          add this to your application :



                                          @app.route('/logout')
                                          def logout():
                                          return ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'})






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Sep 18 '15 at 13:29









                                          Amir Mofakhar

                                          3,656284




                                          3,656284












                                          • better to use this return : return('Logout', 401)
                                            – Amir Mofakhar
                                            Sep 18 '15 at 13:35


















                                          • better to use this return : return('Logout', 401)
                                            – Amir Mofakhar
                                            Sep 18 '15 at 13:35
















                                          better to use this return : return('Logout', 401)
                                          – Amir Mofakhar
                                          Sep 18 '15 at 13:35




                                          better to use this return : return('Logout', 401)
                                          – Amir Mofakhar
                                          Sep 18 '15 at 13:35










                                          up vote
                                          1
                                          down vote













                                          All you need is redirect user on some logout URL and return 401 Unauthorized error on it. On error page (which must be accessible without basic auth) you need to provide a full link to your home page (including scheme and hostname). User will click this link and browser will ask for credentials again.



                                          Example for Nginx:



                                          location /logout {
                                          return 401;
                                          }

                                          error_page 401 /errors/401.html;

                                          location /errors {
                                          auth_basic off;
                                          ssi on;
                                          ssi_types text/html;
                                          alias /home/user/errors;
                                          }


                                          Error page /home/user/errors/401.html:



                                          <!DOCTYPE html>
                                          <p>You're not authorised. <a href="<!--# echo var="scheme" -->://<!--# echo var="host" -->/">Login</a>.</p>





                                          share|improve this answer

























                                            up vote
                                            1
                                            down vote













                                            All you need is redirect user on some logout URL and return 401 Unauthorized error on it. On error page (which must be accessible without basic auth) you need to provide a full link to your home page (including scheme and hostname). User will click this link and browser will ask for credentials again.



                                            Example for Nginx:



                                            location /logout {
                                            return 401;
                                            }

                                            error_page 401 /errors/401.html;

                                            location /errors {
                                            auth_basic off;
                                            ssi on;
                                            ssi_types text/html;
                                            alias /home/user/errors;
                                            }


                                            Error page /home/user/errors/401.html:



                                            <!DOCTYPE html>
                                            <p>You're not authorised. <a href="<!--# echo var="scheme" -->://<!--# echo var="host" -->/">Login</a>.</p>





                                            share|improve this answer























                                              up vote
                                              1
                                              down vote










                                              up vote
                                              1
                                              down vote









                                              All you need is redirect user on some logout URL and return 401 Unauthorized error on it. On error page (which must be accessible without basic auth) you need to provide a full link to your home page (including scheme and hostname). User will click this link and browser will ask for credentials again.



                                              Example for Nginx:



                                              location /logout {
                                              return 401;
                                              }

                                              error_page 401 /errors/401.html;

                                              location /errors {
                                              auth_basic off;
                                              ssi on;
                                              ssi_types text/html;
                                              alias /home/user/errors;
                                              }


                                              Error page /home/user/errors/401.html:



                                              <!DOCTYPE html>
                                              <p>You're not authorised. <a href="<!--# echo var="scheme" -->://<!--# echo var="host" -->/">Login</a>.</p>





                                              share|improve this answer












                                              All you need is redirect user on some logout URL and return 401 Unauthorized error on it. On error page (which must be accessible without basic auth) you need to provide a full link to your home page (including scheme and hostname). User will click this link and browser will ask for credentials again.



                                              Example for Nginx:



                                              location /logout {
                                              return 401;
                                              }

                                              error_page 401 /errors/401.html;

                                              location /errors {
                                              auth_basic off;
                                              ssi on;
                                              ssi_types text/html;
                                              alias /home/user/errors;
                                              }


                                              Error page /home/user/errors/401.html:



                                              <!DOCTYPE html>
                                              <p>You're not authorised. <a href="<!--# echo var="scheme" -->://<!--# echo var="host" -->/">Login</a>.</p>






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Dec 12 '15 at 14:12









                                              Envek

                                              1,85211629




                                              1,85211629






















                                                  up vote
                                                  1
                                                  down vote













                                                  Based on what I read above I got a simple solution that works on any browser:



                                                  1) on you logout page you call an ajax to your login back end. Your login back end must accept logout user. Once the back end accept, the browser clear the current user and assumes the "logout" user.



                                                  $.ajax({
                                                  async: false,
                                                  url: 'http://your_login_backend',
                                                  type: 'GET',
                                                  username: 'logout'
                                                  });

                                                  setTimeout(function () {
                                                  window.location.href = 'http://normal_index';
                                                  }, 200);


                                                  2) Now when the user got back to the normal index file it will try to automatic enter in the system with the user "logout", on this second time you must block it by reply with 401 to invoke the login/password dialog.



                                                  3) There are many ways to do that, I created two login back ends, one that accepts the logout user and one that doesn't. My normal login page use the one that doesn't accept, my logout page use the one that accepts it.






                                                  share|improve this answer



























                                                    up vote
                                                    1
                                                    down vote













                                                    Based on what I read above I got a simple solution that works on any browser:



                                                    1) on you logout page you call an ajax to your login back end. Your login back end must accept logout user. Once the back end accept, the browser clear the current user and assumes the "logout" user.



                                                    $.ajax({
                                                    async: false,
                                                    url: 'http://your_login_backend',
                                                    type: 'GET',
                                                    username: 'logout'
                                                    });

                                                    setTimeout(function () {
                                                    window.location.href = 'http://normal_index';
                                                    }, 200);


                                                    2) Now when the user got back to the normal index file it will try to automatic enter in the system with the user "logout", on this second time you must block it by reply with 401 to invoke the login/password dialog.



                                                    3) There are many ways to do that, I created two login back ends, one that accepts the logout user and one that doesn't. My normal login page use the one that doesn't accept, my logout page use the one that accepts it.






                                                    share|improve this answer

























                                                      up vote
                                                      1
                                                      down vote










                                                      up vote
                                                      1
                                                      down vote









                                                      Based on what I read above I got a simple solution that works on any browser:



                                                      1) on you logout page you call an ajax to your login back end. Your login back end must accept logout user. Once the back end accept, the browser clear the current user and assumes the "logout" user.



                                                      $.ajax({
                                                      async: false,
                                                      url: 'http://your_login_backend',
                                                      type: 'GET',
                                                      username: 'logout'
                                                      });

                                                      setTimeout(function () {
                                                      window.location.href = 'http://normal_index';
                                                      }, 200);


                                                      2) Now when the user got back to the normal index file it will try to automatic enter in the system with the user "logout", on this second time you must block it by reply with 401 to invoke the login/password dialog.



                                                      3) There are many ways to do that, I created two login back ends, one that accepts the logout user and one that doesn't. My normal login page use the one that doesn't accept, my logout page use the one that accepts it.






                                                      share|improve this answer














                                                      Based on what I read above I got a simple solution that works on any browser:



                                                      1) on you logout page you call an ajax to your login back end. Your login back end must accept logout user. Once the back end accept, the browser clear the current user and assumes the "logout" user.



                                                      $.ajax({
                                                      async: false,
                                                      url: 'http://your_login_backend',
                                                      type: 'GET',
                                                      username: 'logout'
                                                      });

                                                      setTimeout(function () {
                                                      window.location.href = 'http://normal_index';
                                                      }, 200);


                                                      2) Now when the user got back to the normal index file it will try to automatic enter in the system with the user "logout", on this second time you must block it by reply with 401 to invoke the login/password dialog.



                                                      3) There are many ways to do that, I created two login back ends, one that accepts the logout user and one that doesn't. My normal login page use the one that doesn't accept, my logout page use the one that accepts it.







                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Mar 2 '17 at 15:54

























                                                      answered Mar 2 '17 at 15:45









                                                      Foad

                                                      37136




                                                      37136






















                                                          up vote
                                                          0
                                                          down vote














                                                          • use a session ID (cookie)

                                                          • invalidate the session ID on the server

                                                          • Don't accept users with invalid session IDs






                                                          share|improve this answer





















                                                          • It's also good to offer Basic Authentication as a backup login scheme for when cookies aren't available.
                                                            – bobince
                                                            Oct 24 '08 at 13:35






                                                          • 6




                                                            Invalidating session doesn't work, see other comments.
                                                            – Marko
                                                            Oct 24 '08 at 14:08















                                                          up vote
                                                          0
                                                          down vote














                                                          • use a session ID (cookie)

                                                          • invalidate the session ID on the server

                                                          • Don't accept users with invalid session IDs






                                                          share|improve this answer





















                                                          • It's also good to offer Basic Authentication as a backup login scheme for when cookies aren't available.
                                                            – bobince
                                                            Oct 24 '08 at 13:35






                                                          • 6




                                                            Invalidating session doesn't work, see other comments.
                                                            – Marko
                                                            Oct 24 '08 at 14:08













                                                          up vote
                                                          0
                                                          down vote










                                                          up vote
                                                          0
                                                          down vote










                                                          • use a session ID (cookie)

                                                          • invalidate the session ID on the server

                                                          • Don't accept users with invalid session IDs






                                                          share|improve this answer













                                                          • use a session ID (cookie)

                                                          • invalidate the session ID on the server

                                                          • Don't accept users with invalid session IDs







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Oct 24 '08 at 13:24









                                                          Tomalak

                                                          255k51423539




                                                          255k51423539












                                                          • It's also good to offer Basic Authentication as a backup login scheme for when cookies aren't available.
                                                            – bobince
                                                            Oct 24 '08 at 13:35






                                                          • 6




                                                            Invalidating session doesn't work, see other comments.
                                                            – Marko
                                                            Oct 24 '08 at 14:08


















                                                          • It's also good to offer Basic Authentication as a backup login scheme for when cookies aren't available.
                                                            – bobince
                                                            Oct 24 '08 at 13:35






                                                          • 6




                                                            Invalidating session doesn't work, see other comments.
                                                            – Marko
                                                            Oct 24 '08 at 14:08
















                                                          It's also good to offer Basic Authentication as a backup login scheme for when cookies aren't available.
                                                          – bobince
                                                          Oct 24 '08 at 13:35




                                                          It's also good to offer Basic Authentication as a backup login scheme for when cookies aren't available.
                                                          – bobince
                                                          Oct 24 '08 at 13:35




                                                          6




                                                          6




                                                          Invalidating session doesn't work, see other comments.
                                                          – Marko
                                                          Oct 24 '08 at 14:08




                                                          Invalidating session doesn't work, see other comments.
                                                          – Marko
                                                          Oct 24 '08 at 14:08










                                                          up vote
                                                          0
                                                          down vote













                                                          This JavaScript must be working for all latest version browsers:



                                                          //Detect Browser
                                                          var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                                                          // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
                                                          var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
                                                          var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                                                          // At least Safari 3+: "[object HTMLElementConstructor]"
                                                          var isChrome = !!window.chrome && !isOpera; // Chrome 1+
                                                          var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
                                                          var Host = window.location.host;


                                                          //Clear Basic Realm Authentication
                                                          if(isIE){
                                                          //IE
                                                          document.execCommand("ClearAuthenticationCache");
                                                          window.location = '/';
                                                          }
                                                          else if(isSafari)
                                                          {//Safari. but this works mostly on all browser except chrome
                                                          (function(safeLocation){
                                                          var outcome, u, m = "You should be logged out now.";
                                                          // IE has a simple solution for it - API:
                                                          try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
                                                          // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
                                                          if (!outcome) {
                                                          // Let's create an xmlhttp object
                                                          outcome = (function(x){
                                                          if (x) {
                                                          // the reason we use "random" value for password is
                                                          // that browsers cache requests. changing
                                                          // password effectively behaves like cache-busing.
                                                          x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                                                          x.send("");
                                                          // x.abort()
                                                          return 1 // this is **speculative** "We are done."
                                                          } else {
                                                          return
                                                          }
                                                          })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
                                                          }
                                                          if (!outcome) {
                                                          m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
                                                          }
                                                          alert(m);
                                                          window.location = '/';
                                                          // return !!outcome
                                                          })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)
                                                          }
                                                          else{
                                                          //Firefox,Chrome
                                                          window.location = 'http://log:out@'+Host+'/';
                                                          }





                                                          share|improve this answer

























                                                            up vote
                                                            0
                                                            down vote













                                                            This JavaScript must be working for all latest version browsers:



                                                            //Detect Browser
                                                            var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                                                            // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
                                                            var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
                                                            var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                                                            // At least Safari 3+: "[object HTMLElementConstructor]"
                                                            var isChrome = !!window.chrome && !isOpera; // Chrome 1+
                                                            var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
                                                            var Host = window.location.host;


                                                            //Clear Basic Realm Authentication
                                                            if(isIE){
                                                            //IE
                                                            document.execCommand("ClearAuthenticationCache");
                                                            window.location = '/';
                                                            }
                                                            else if(isSafari)
                                                            {//Safari. but this works mostly on all browser except chrome
                                                            (function(safeLocation){
                                                            var outcome, u, m = "You should be logged out now.";
                                                            // IE has a simple solution for it - API:
                                                            try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
                                                            // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
                                                            if (!outcome) {
                                                            // Let's create an xmlhttp object
                                                            outcome = (function(x){
                                                            if (x) {
                                                            // the reason we use "random" value for password is
                                                            // that browsers cache requests. changing
                                                            // password effectively behaves like cache-busing.
                                                            x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                                                            x.send("");
                                                            // x.abort()
                                                            return 1 // this is **speculative** "We are done."
                                                            } else {
                                                            return
                                                            }
                                                            })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
                                                            }
                                                            if (!outcome) {
                                                            m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
                                                            }
                                                            alert(m);
                                                            window.location = '/';
                                                            // return !!outcome
                                                            })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)
                                                            }
                                                            else{
                                                            //Firefox,Chrome
                                                            window.location = 'http://log:out@'+Host+'/';
                                                            }





                                                            share|improve this answer























                                                              up vote
                                                              0
                                                              down vote










                                                              up vote
                                                              0
                                                              down vote









                                                              This JavaScript must be working for all latest version browsers:



                                                              //Detect Browser
                                                              var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                                                              // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
                                                              var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
                                                              var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                                                              // At least Safari 3+: "[object HTMLElementConstructor]"
                                                              var isChrome = !!window.chrome && !isOpera; // Chrome 1+
                                                              var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
                                                              var Host = window.location.host;


                                                              //Clear Basic Realm Authentication
                                                              if(isIE){
                                                              //IE
                                                              document.execCommand("ClearAuthenticationCache");
                                                              window.location = '/';
                                                              }
                                                              else if(isSafari)
                                                              {//Safari. but this works mostly on all browser except chrome
                                                              (function(safeLocation){
                                                              var outcome, u, m = "You should be logged out now.";
                                                              // IE has a simple solution for it - API:
                                                              try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
                                                              // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
                                                              if (!outcome) {
                                                              // Let's create an xmlhttp object
                                                              outcome = (function(x){
                                                              if (x) {
                                                              // the reason we use "random" value for password is
                                                              // that browsers cache requests. changing
                                                              // password effectively behaves like cache-busing.
                                                              x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                                                              x.send("");
                                                              // x.abort()
                                                              return 1 // this is **speculative** "We are done."
                                                              } else {
                                                              return
                                                              }
                                                              })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
                                                              }
                                                              if (!outcome) {
                                                              m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
                                                              }
                                                              alert(m);
                                                              window.location = '/';
                                                              // return !!outcome
                                                              })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)
                                                              }
                                                              else{
                                                              //Firefox,Chrome
                                                              window.location = 'http://log:out@'+Host+'/';
                                                              }





                                                              share|improve this answer












                                                              This JavaScript must be working for all latest version browsers:



                                                              //Detect Browser
                                                              var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                                                              // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
                                                              var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
                                                              var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                                                              // At least Safari 3+: "[object HTMLElementConstructor]"
                                                              var isChrome = !!window.chrome && !isOpera; // Chrome 1+
                                                              var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
                                                              var Host = window.location.host;


                                                              //Clear Basic Realm Authentication
                                                              if(isIE){
                                                              //IE
                                                              document.execCommand("ClearAuthenticationCache");
                                                              window.location = '/';
                                                              }
                                                              else if(isSafari)
                                                              {//Safari. but this works mostly on all browser except chrome
                                                              (function(safeLocation){
                                                              var outcome, u, m = "You should be logged out now.";
                                                              // IE has a simple solution for it - API:
                                                              try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
                                                              // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
                                                              if (!outcome) {
                                                              // Let's create an xmlhttp object
                                                              outcome = (function(x){
                                                              if (x) {
                                                              // the reason we use "random" value for password is
                                                              // that browsers cache requests. changing
                                                              // password effectively behaves like cache-busing.
                                                              x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                                                              x.send("");
                                                              // x.abort()
                                                              return 1 // this is **speculative** "We are done."
                                                              } else {
                                                              return
                                                              }
                                                              })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u ))
                                                              }
                                                              if (!outcome) {
                                                              m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
                                                              }
                                                              alert(m);
                                                              window.location = '/';
                                                              // return !!outcome
                                                              })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)
                                                              }
                                                              else{
                                                              //Firefox,Chrome
                                                              window.location = 'http://log:out@'+Host+'/';
                                                              }






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Jul 21 '15 at 5:16









                                                              Amit Shah

                                                              1




                                                              1






















                                                                  up vote
                                                                  0
                                                                  down vote













                                                                  I updated mthoring's solution for modern Chrome versions:



                                                                  function logout(secUrl, redirUrl) {
                                                                  if (bowser.msie) {
                                                                  document.execCommand('ClearAuthenticationCache', 'false');
                                                                  } else if (bowser.gecko) {
                                                                  $.ajax({
                                                                  async: false,
                                                                  url: secUrl,
                                                                  type: 'GET',
                                                                  username: 'logout'
                                                                  });
                                                                  } else if (bowser.webkit || bowser.chrome) {
                                                                  var xmlhttp = new XMLHttpRequest();
                                                                  xmlhttp.open("GET", secUrl, true);
                                                                  xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                  xmlhttp.send();
                                                                  } else {
                                                                  // http://stackoverflow.com/questions/5957822/how-to-clear-basic-authentication-details-in-chrome
                                                                  redirUrl = url.replace('http://', 'http://' + new Date().getTime() + '@');
                                                                  }
                                                                  setTimeout(function () {
                                                                  window.location.href = redirUrl;
                                                                  }, 200);
                                                                  }





                                                                  share|improve this answer

























                                                                    up vote
                                                                    0
                                                                    down vote













                                                                    I updated mthoring's solution for modern Chrome versions:



                                                                    function logout(secUrl, redirUrl) {
                                                                    if (bowser.msie) {
                                                                    document.execCommand('ClearAuthenticationCache', 'false');
                                                                    } else if (bowser.gecko) {
                                                                    $.ajax({
                                                                    async: false,
                                                                    url: secUrl,
                                                                    type: 'GET',
                                                                    username: 'logout'
                                                                    });
                                                                    } else if (bowser.webkit || bowser.chrome) {
                                                                    var xmlhttp = new XMLHttpRequest();
                                                                    xmlhttp.open("GET", secUrl, true);
                                                                    xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                    xmlhttp.send();
                                                                    } else {
                                                                    // http://stackoverflow.com/questions/5957822/how-to-clear-basic-authentication-details-in-chrome
                                                                    redirUrl = url.replace('http://', 'http://' + new Date().getTime() + '@');
                                                                    }
                                                                    setTimeout(function () {
                                                                    window.location.href = redirUrl;
                                                                    }, 200);
                                                                    }





                                                                    share|improve this answer























                                                                      up vote
                                                                      0
                                                                      down vote










                                                                      up vote
                                                                      0
                                                                      down vote









                                                                      I updated mthoring's solution for modern Chrome versions:



                                                                      function logout(secUrl, redirUrl) {
                                                                      if (bowser.msie) {
                                                                      document.execCommand('ClearAuthenticationCache', 'false');
                                                                      } else if (bowser.gecko) {
                                                                      $.ajax({
                                                                      async: false,
                                                                      url: secUrl,
                                                                      type: 'GET',
                                                                      username: 'logout'
                                                                      });
                                                                      } else if (bowser.webkit || bowser.chrome) {
                                                                      var xmlhttp = new XMLHttpRequest();
                                                                      xmlhttp.open("GET", secUrl, true);
                                                                      xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                      xmlhttp.send();
                                                                      } else {
                                                                      // http://stackoverflow.com/questions/5957822/how-to-clear-basic-authentication-details-in-chrome
                                                                      redirUrl = url.replace('http://', 'http://' + new Date().getTime() + '@');
                                                                      }
                                                                      setTimeout(function () {
                                                                      window.location.href = redirUrl;
                                                                      }, 200);
                                                                      }





                                                                      share|improve this answer












                                                                      I updated mthoring's solution for modern Chrome versions:



                                                                      function logout(secUrl, redirUrl) {
                                                                      if (bowser.msie) {
                                                                      document.execCommand('ClearAuthenticationCache', 'false');
                                                                      } else if (bowser.gecko) {
                                                                      $.ajax({
                                                                      async: false,
                                                                      url: secUrl,
                                                                      type: 'GET',
                                                                      username: 'logout'
                                                                      });
                                                                      } else if (bowser.webkit || bowser.chrome) {
                                                                      var xmlhttp = new XMLHttpRequest();
                                                                      xmlhttp.open("GET", secUrl, true);
                                                                      xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                      xmlhttp.send();
                                                                      } else {
                                                                      // http://stackoverflow.com/questions/5957822/how-to-clear-basic-authentication-details-in-chrome
                                                                      redirUrl = url.replace('http://', 'http://' + new Date().getTime() + '@');
                                                                      }
                                                                      setTimeout(function () {
                                                                      window.location.href = redirUrl;
                                                                      }, 200);
                                                                      }






                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered May 15 '17 at 23:15









                                                                      Max

                                                                      596613




                                                                      596613






















                                                                          up vote
                                                                          0
                                                                          down vote















                                                                              function logout(secUrl, redirUrl) {
                                                                          if (bowser.msie) {
                                                                          document.execCommand('ClearAuthenticationCache', 'false');
                                                                          } else if (bowser.gecko) {
                                                                          $.ajax({
                                                                          async: false,
                                                                          url: secUrl,
                                                                          type: 'GET',
                                                                          username: 'logout'
                                                                          });
                                                                          } else if (bowser.webkit) {
                                                                          var xmlhttp = new XMLHttpRequest();
                                                                          xmlhttp.open("GET", secUrl, true);
                                                                          xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                          xmlhttp.send();
                                                                          } else {
                                                                          alert("Logging out automatically is unsupported for " + bowser.name
                                                                          + "nYou must close the browser to log out.");
                                                                          }
                                                                          setTimeout(function () {
                                                                          window.location.href = redirUrl;
                                                                          }, 200);
                                                                          }






                                                                          I tried using the above in the following way.



                                                                          ?php
                                                                          ob_start();
                                                                          session_start();
                                                                          require_once 'dbconnect.php';

                                                                          // if session is not set this will redirect to login page
                                                                          if( !isset($_SESSION['user']) ) {
                                                                          header("Location: index.php");
                                                                          exit;
                                                                          }
                                                                          // select loggedin users detail
                                                                          $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
                                                                          $userRow=mysql_fetch_array($res);
                                                                          ?>
                                                                          <!DOCTYPE html>
                                                                          <html>
                                                                          <head>
                                                                          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                                                                          <title>Welcome - <?php echo $userRow['userEmail']; ?></title>
                                                                          <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
                                                                          <link rel="stylesheet" href="style.css" type="text/css" />

                                                                          <script src="assets/js/bowser.min.js"></script>
                                                                          <script>
                                                                          //function logout(secUrl, redirUrl)
                                                                          //bowser = require('bowser');
                                                                          function logout(secUrl, redirUrl) {
                                                                          alert(redirUrl);
                                                                          if (bowser.msie) {
                                                                          document.execCommand('ClearAuthenticationCache', 'false');
                                                                          } else if (bowser.gecko) {
                                                                          $.ajax({
                                                                          async: false,
                                                                          url: secUrl,
                                                                          type: 'GET',
                                                                          username: 'logout'
                                                                          });
                                                                          } else if (bowser.webkit) {
                                                                          var xmlhttp = new XMLHttpRequest();
                                                                          xmlhttp.open("GET", secUrl, true);
                                                                          xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                          xmlhttp.send();
                                                                          } else {
                                                                          alert("Logging out automatically is unsupported for " + bowser.name
                                                                          + "nYou must close the browser to log out.");
                                                                          }
                                                                          window.location.assign(redirUrl);
                                                                          /*setTimeout(function () {
                                                                          window.location.href = redirUrl;
                                                                          }, 200);*/
                                                                          }


                                                                          function f1()
                                                                          {
                                                                          alert("f1 called");
                                                                          //form validation that recalls the page showing with supplied inputs.
                                                                          }
                                                                          </script>
                                                                          </head>
                                                                          <body>

                                                                          <nav class="navbar navbar-default navbar-fixed-top">
                                                                          <div class="container">
                                                                          <div class="navbar-header">
                                                                          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                                                                          <span class="sr-only">Toggle navigation</span>
                                                                          <span class="icon-bar"></span>
                                                                          <span class="icon-bar"></span>
                                                                          <span class="icon-bar"></span>
                                                                          </button>
                                                                          <a class="navbar-brand" href="http://www.codingcage.com">Coding Cage</a>
                                                                          </div>
                                                                          <div id="navbar" class="navbar-collapse collapse">
                                                                          <ul class="nav navbar-nav">
                                                                          <li class="active"><a href="http://www.codingcage.com/2015/01/user-registration-and-login-script-using-php-mysql.html">Back to Article</a></li>
                                                                          <li><a href="http://www.codingcage.com/search/label/jQuery">jQuery</a></li>
                                                                          <li><a href="http://www.codingcage.com/search/label/PHP">PHP</a></li>
                                                                          </ul>
                                                                          <ul class="nav navbar-nav navbar-right">

                                                                          <li class="dropdown">
                                                                          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                                                                          <span class="glyphicon glyphicon-user"></span>&nbsp;Hi' <?php echo $userRow['userEmail']; ?>&nbsp;<span class="caret"></span></a>
                                                                          <ul class="dropdown-menu">
                                                                          <li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Sign Out</a></li>
                                                                          </ul>
                                                                          </li>
                                                                          </ul>
                                                                          </div><!--/.nav-collapse -->
                                                                          </div>
                                                                          </nav>

                                                                          <div id="wrapper">

                                                                          <div class="container">

                                                                          <div class="page-header">
                                                                          <h3>Coding Cage - Programming Blog</h3>
                                                                          </div>

                                                                          <div class="row">
                                                                          <div class="col-lg-12" id="div_logout">
                                                                          <h1 onclick="logout(window.location.href, 'www.espncricinfo.com')">MichaelA1S1! Click here to see log out functionality upon click inside div</h1>
                                                                          </div>
                                                                          </div>

                                                                          </div>

                                                                          </div>

                                                                          <script src="assets/jquery-1.11.3-jquery.min.js"></script>
                                                                          <script src="assets/js/bootstrap.min.js"></script>


                                                                          </body>
                                                                          </html>
                                                                          <?php ob_end_flush(); ?>


                                                                          But it only redirects you to new location. No logout.






                                                                          share|improve this answer



























                                                                            up vote
                                                                            0
                                                                            down vote















                                                                                function logout(secUrl, redirUrl) {
                                                                            if (bowser.msie) {
                                                                            document.execCommand('ClearAuthenticationCache', 'false');
                                                                            } else if (bowser.gecko) {
                                                                            $.ajax({
                                                                            async: false,
                                                                            url: secUrl,
                                                                            type: 'GET',
                                                                            username: 'logout'
                                                                            });
                                                                            } else if (bowser.webkit) {
                                                                            var xmlhttp = new XMLHttpRequest();
                                                                            xmlhttp.open("GET", secUrl, true);
                                                                            xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                            xmlhttp.send();
                                                                            } else {
                                                                            alert("Logging out automatically is unsupported for " + bowser.name
                                                                            + "nYou must close the browser to log out.");
                                                                            }
                                                                            setTimeout(function () {
                                                                            window.location.href = redirUrl;
                                                                            }, 200);
                                                                            }






                                                                            I tried using the above in the following way.



                                                                            ?php
                                                                            ob_start();
                                                                            session_start();
                                                                            require_once 'dbconnect.php';

                                                                            // if session is not set this will redirect to login page
                                                                            if( !isset($_SESSION['user']) ) {
                                                                            header("Location: index.php");
                                                                            exit;
                                                                            }
                                                                            // select loggedin users detail
                                                                            $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
                                                                            $userRow=mysql_fetch_array($res);
                                                                            ?>
                                                                            <!DOCTYPE html>
                                                                            <html>
                                                                            <head>
                                                                            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                                                                            <title>Welcome - <?php echo $userRow['userEmail']; ?></title>
                                                                            <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
                                                                            <link rel="stylesheet" href="style.css" type="text/css" />

                                                                            <script src="assets/js/bowser.min.js"></script>
                                                                            <script>
                                                                            //function logout(secUrl, redirUrl)
                                                                            //bowser = require('bowser');
                                                                            function logout(secUrl, redirUrl) {
                                                                            alert(redirUrl);
                                                                            if (bowser.msie) {
                                                                            document.execCommand('ClearAuthenticationCache', 'false');
                                                                            } else if (bowser.gecko) {
                                                                            $.ajax({
                                                                            async: false,
                                                                            url: secUrl,
                                                                            type: 'GET',
                                                                            username: 'logout'
                                                                            });
                                                                            } else if (bowser.webkit) {
                                                                            var xmlhttp = new XMLHttpRequest();
                                                                            xmlhttp.open("GET", secUrl, true);
                                                                            xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                            xmlhttp.send();
                                                                            } else {
                                                                            alert("Logging out automatically is unsupported for " + bowser.name
                                                                            + "nYou must close the browser to log out.");
                                                                            }
                                                                            window.location.assign(redirUrl);
                                                                            /*setTimeout(function () {
                                                                            window.location.href = redirUrl;
                                                                            }, 200);*/
                                                                            }


                                                                            function f1()
                                                                            {
                                                                            alert("f1 called");
                                                                            //form validation that recalls the page showing with supplied inputs.
                                                                            }
                                                                            </script>
                                                                            </head>
                                                                            <body>

                                                                            <nav class="navbar navbar-default navbar-fixed-top">
                                                                            <div class="container">
                                                                            <div class="navbar-header">
                                                                            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                                                                            <span class="sr-only">Toggle navigation</span>
                                                                            <span class="icon-bar"></span>
                                                                            <span class="icon-bar"></span>
                                                                            <span class="icon-bar"></span>
                                                                            </button>
                                                                            <a class="navbar-brand" href="http://www.codingcage.com">Coding Cage</a>
                                                                            </div>
                                                                            <div id="navbar" class="navbar-collapse collapse">
                                                                            <ul class="nav navbar-nav">
                                                                            <li class="active"><a href="http://www.codingcage.com/2015/01/user-registration-and-login-script-using-php-mysql.html">Back to Article</a></li>
                                                                            <li><a href="http://www.codingcage.com/search/label/jQuery">jQuery</a></li>
                                                                            <li><a href="http://www.codingcage.com/search/label/PHP">PHP</a></li>
                                                                            </ul>
                                                                            <ul class="nav navbar-nav navbar-right">

                                                                            <li class="dropdown">
                                                                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                                                                            <span class="glyphicon glyphicon-user"></span>&nbsp;Hi' <?php echo $userRow['userEmail']; ?>&nbsp;<span class="caret"></span></a>
                                                                            <ul class="dropdown-menu">
                                                                            <li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Sign Out</a></li>
                                                                            </ul>
                                                                            </li>
                                                                            </ul>
                                                                            </div><!--/.nav-collapse -->
                                                                            </div>
                                                                            </nav>

                                                                            <div id="wrapper">

                                                                            <div class="container">

                                                                            <div class="page-header">
                                                                            <h3>Coding Cage - Programming Blog</h3>
                                                                            </div>

                                                                            <div class="row">
                                                                            <div class="col-lg-12" id="div_logout">
                                                                            <h1 onclick="logout(window.location.href, 'www.espncricinfo.com')">MichaelA1S1! Click here to see log out functionality upon click inside div</h1>
                                                                            </div>
                                                                            </div>

                                                                            </div>

                                                                            </div>

                                                                            <script src="assets/jquery-1.11.3-jquery.min.js"></script>
                                                                            <script src="assets/js/bootstrap.min.js"></script>


                                                                            </body>
                                                                            </html>
                                                                            <?php ob_end_flush(); ?>


                                                                            But it only redirects you to new location. No logout.






                                                                            share|improve this answer

























                                                                              up vote
                                                                              0
                                                                              down vote










                                                                              up vote
                                                                              0
                                                                              down vote











                                                                                  function logout(secUrl, redirUrl) {
                                                                              if (bowser.msie) {
                                                                              document.execCommand('ClearAuthenticationCache', 'false');
                                                                              } else if (bowser.gecko) {
                                                                              $.ajax({
                                                                              async: false,
                                                                              url: secUrl,
                                                                              type: 'GET',
                                                                              username: 'logout'
                                                                              });
                                                                              } else if (bowser.webkit) {
                                                                              var xmlhttp = new XMLHttpRequest();
                                                                              xmlhttp.open("GET", secUrl, true);
                                                                              xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                              xmlhttp.send();
                                                                              } else {
                                                                              alert("Logging out automatically is unsupported for " + bowser.name
                                                                              + "nYou must close the browser to log out.");
                                                                              }
                                                                              setTimeout(function () {
                                                                              window.location.href = redirUrl;
                                                                              }, 200);
                                                                              }






                                                                              I tried using the above in the following way.



                                                                              ?php
                                                                              ob_start();
                                                                              session_start();
                                                                              require_once 'dbconnect.php';

                                                                              // if session is not set this will redirect to login page
                                                                              if( !isset($_SESSION['user']) ) {
                                                                              header("Location: index.php");
                                                                              exit;
                                                                              }
                                                                              // select loggedin users detail
                                                                              $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
                                                                              $userRow=mysql_fetch_array($res);
                                                                              ?>
                                                                              <!DOCTYPE html>
                                                                              <html>
                                                                              <head>
                                                                              <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                                                                              <title>Welcome - <?php echo $userRow['userEmail']; ?></title>
                                                                              <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
                                                                              <link rel="stylesheet" href="style.css" type="text/css" />

                                                                              <script src="assets/js/bowser.min.js"></script>
                                                                              <script>
                                                                              //function logout(secUrl, redirUrl)
                                                                              //bowser = require('bowser');
                                                                              function logout(secUrl, redirUrl) {
                                                                              alert(redirUrl);
                                                                              if (bowser.msie) {
                                                                              document.execCommand('ClearAuthenticationCache', 'false');
                                                                              } else if (bowser.gecko) {
                                                                              $.ajax({
                                                                              async: false,
                                                                              url: secUrl,
                                                                              type: 'GET',
                                                                              username: 'logout'
                                                                              });
                                                                              } else if (bowser.webkit) {
                                                                              var xmlhttp = new XMLHttpRequest();
                                                                              xmlhttp.open("GET", secUrl, true);
                                                                              xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                              xmlhttp.send();
                                                                              } else {
                                                                              alert("Logging out automatically is unsupported for " + bowser.name
                                                                              + "nYou must close the browser to log out.");
                                                                              }
                                                                              window.location.assign(redirUrl);
                                                                              /*setTimeout(function () {
                                                                              window.location.href = redirUrl;
                                                                              }, 200);*/
                                                                              }


                                                                              function f1()
                                                                              {
                                                                              alert("f1 called");
                                                                              //form validation that recalls the page showing with supplied inputs.
                                                                              }
                                                                              </script>
                                                                              </head>
                                                                              <body>

                                                                              <nav class="navbar navbar-default navbar-fixed-top">
                                                                              <div class="container">
                                                                              <div class="navbar-header">
                                                                              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                                                                              <span class="sr-only">Toggle navigation</span>
                                                                              <span class="icon-bar"></span>
                                                                              <span class="icon-bar"></span>
                                                                              <span class="icon-bar"></span>
                                                                              </button>
                                                                              <a class="navbar-brand" href="http://www.codingcage.com">Coding Cage</a>
                                                                              </div>
                                                                              <div id="navbar" class="navbar-collapse collapse">
                                                                              <ul class="nav navbar-nav">
                                                                              <li class="active"><a href="http://www.codingcage.com/2015/01/user-registration-and-login-script-using-php-mysql.html">Back to Article</a></li>
                                                                              <li><a href="http://www.codingcage.com/search/label/jQuery">jQuery</a></li>
                                                                              <li><a href="http://www.codingcage.com/search/label/PHP">PHP</a></li>
                                                                              </ul>
                                                                              <ul class="nav navbar-nav navbar-right">

                                                                              <li class="dropdown">
                                                                              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                                                                              <span class="glyphicon glyphicon-user"></span>&nbsp;Hi' <?php echo $userRow['userEmail']; ?>&nbsp;<span class="caret"></span></a>
                                                                              <ul class="dropdown-menu">
                                                                              <li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Sign Out</a></li>
                                                                              </ul>
                                                                              </li>
                                                                              </ul>
                                                                              </div><!--/.nav-collapse -->
                                                                              </div>
                                                                              </nav>

                                                                              <div id="wrapper">

                                                                              <div class="container">

                                                                              <div class="page-header">
                                                                              <h3>Coding Cage - Programming Blog</h3>
                                                                              </div>

                                                                              <div class="row">
                                                                              <div class="col-lg-12" id="div_logout">
                                                                              <h1 onclick="logout(window.location.href, 'www.espncricinfo.com')">MichaelA1S1! Click here to see log out functionality upon click inside div</h1>
                                                                              </div>
                                                                              </div>

                                                                              </div>

                                                                              </div>

                                                                              <script src="assets/jquery-1.11.3-jquery.min.js"></script>
                                                                              <script src="assets/js/bootstrap.min.js"></script>


                                                                              </body>
                                                                              </html>
                                                                              <?php ob_end_flush(); ?>


                                                                              But it only redirects you to new location. No logout.






                                                                              share|improve this answer
















                                                                                  function logout(secUrl, redirUrl) {
                                                                              if (bowser.msie) {
                                                                              document.execCommand('ClearAuthenticationCache', 'false');
                                                                              } else if (bowser.gecko) {
                                                                              $.ajax({
                                                                              async: false,
                                                                              url: secUrl,
                                                                              type: 'GET',
                                                                              username: 'logout'
                                                                              });
                                                                              } else if (bowser.webkit) {
                                                                              var xmlhttp = new XMLHttpRequest();
                                                                              xmlhttp.open("GET", secUrl, true);
                                                                              xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                              xmlhttp.send();
                                                                              } else {
                                                                              alert("Logging out automatically is unsupported for " + bowser.name
                                                                              + "nYou must close the browser to log out.");
                                                                              }
                                                                              setTimeout(function () {
                                                                              window.location.href = redirUrl;
                                                                              }, 200);
                                                                              }






                                                                              I tried using the above in the following way.



                                                                              ?php
                                                                              ob_start();
                                                                              session_start();
                                                                              require_once 'dbconnect.php';

                                                                              // if session is not set this will redirect to login page
                                                                              if( !isset($_SESSION['user']) ) {
                                                                              header("Location: index.php");
                                                                              exit;
                                                                              }
                                                                              // select loggedin users detail
                                                                              $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
                                                                              $userRow=mysql_fetch_array($res);
                                                                              ?>
                                                                              <!DOCTYPE html>
                                                                              <html>
                                                                              <head>
                                                                              <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                                                                              <title>Welcome - <?php echo $userRow['userEmail']; ?></title>
                                                                              <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
                                                                              <link rel="stylesheet" href="style.css" type="text/css" />

                                                                              <script src="assets/js/bowser.min.js"></script>
                                                                              <script>
                                                                              //function logout(secUrl, redirUrl)
                                                                              //bowser = require('bowser');
                                                                              function logout(secUrl, redirUrl) {
                                                                              alert(redirUrl);
                                                                              if (bowser.msie) {
                                                                              document.execCommand('ClearAuthenticationCache', 'false');
                                                                              } else if (bowser.gecko) {
                                                                              $.ajax({
                                                                              async: false,
                                                                              url: secUrl,
                                                                              type: 'GET',
                                                                              username: 'logout'
                                                                              });
                                                                              } else if (bowser.webkit) {
                                                                              var xmlhttp = new XMLHttpRequest();
                                                                              xmlhttp.open("GET", secUrl, true);
                                                                              xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                              xmlhttp.send();
                                                                              } else {
                                                                              alert("Logging out automatically is unsupported for " + bowser.name
                                                                              + "nYou must close the browser to log out.");
                                                                              }
                                                                              window.location.assign(redirUrl);
                                                                              /*setTimeout(function () {
                                                                              window.location.href = redirUrl;
                                                                              }, 200);*/
                                                                              }


                                                                              function f1()
                                                                              {
                                                                              alert("f1 called");
                                                                              //form validation that recalls the page showing with supplied inputs.
                                                                              }
                                                                              </script>
                                                                              </head>
                                                                              <body>

                                                                              <nav class="navbar navbar-default navbar-fixed-top">
                                                                              <div class="container">
                                                                              <div class="navbar-header">
                                                                              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                                                                              <span class="sr-only">Toggle navigation</span>
                                                                              <span class="icon-bar"></span>
                                                                              <span class="icon-bar"></span>
                                                                              <span class="icon-bar"></span>
                                                                              </button>
                                                                              <a class="navbar-brand" href="http://www.codingcage.com">Coding Cage</a>
                                                                              </div>
                                                                              <div id="navbar" class="navbar-collapse collapse">
                                                                              <ul class="nav navbar-nav">
                                                                              <li class="active"><a href="http://www.codingcage.com/2015/01/user-registration-and-login-script-using-php-mysql.html">Back to Article</a></li>
                                                                              <li><a href="http://www.codingcage.com/search/label/jQuery">jQuery</a></li>
                                                                              <li><a href="http://www.codingcage.com/search/label/PHP">PHP</a></li>
                                                                              </ul>
                                                                              <ul class="nav navbar-nav navbar-right">

                                                                              <li class="dropdown">
                                                                              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                                                                              <span class="glyphicon glyphicon-user"></span>&nbsp;Hi' <?php echo $userRow['userEmail']; ?>&nbsp;<span class="caret"></span></a>
                                                                              <ul class="dropdown-menu">
                                                                              <li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Sign Out</a></li>
                                                                              </ul>
                                                                              </li>
                                                                              </ul>
                                                                              </div><!--/.nav-collapse -->
                                                                              </div>
                                                                              </nav>

                                                                              <div id="wrapper">

                                                                              <div class="container">

                                                                              <div class="page-header">
                                                                              <h3>Coding Cage - Programming Blog</h3>
                                                                              </div>

                                                                              <div class="row">
                                                                              <div class="col-lg-12" id="div_logout">
                                                                              <h1 onclick="logout(window.location.href, 'www.espncricinfo.com')">MichaelA1S1! Click here to see log out functionality upon click inside div</h1>
                                                                              </div>
                                                                              </div>

                                                                              </div>

                                                                              </div>

                                                                              <script src="assets/jquery-1.11.3-jquery.min.js"></script>
                                                                              <script src="assets/js/bootstrap.min.js"></script>


                                                                              </body>
                                                                              </html>
                                                                              <?php ob_end_flush(); ?>


                                                                              But it only redirects you to new location. No logout.






                                                                                  function logout(secUrl, redirUrl) {
                                                                              if (bowser.msie) {
                                                                              document.execCommand('ClearAuthenticationCache', 'false');
                                                                              } else if (bowser.gecko) {
                                                                              $.ajax({
                                                                              async: false,
                                                                              url: secUrl,
                                                                              type: 'GET',
                                                                              username: 'logout'
                                                                              });
                                                                              } else if (bowser.webkit) {
                                                                              var xmlhttp = new XMLHttpRequest();
                                                                              xmlhttp.open("GET", secUrl, true);
                                                                              xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                              xmlhttp.send();
                                                                              } else {
                                                                              alert("Logging out automatically is unsupported for " + bowser.name
                                                                              + "nYou must close the browser to log out.");
                                                                              }
                                                                              setTimeout(function () {
                                                                              window.location.href = redirUrl;
                                                                              }, 200);
                                                                              }





                                                                                  function logout(secUrl, redirUrl) {
                                                                              if (bowser.msie) {
                                                                              document.execCommand('ClearAuthenticationCache', 'false');
                                                                              } else if (bowser.gecko) {
                                                                              $.ajax({
                                                                              async: false,
                                                                              url: secUrl,
                                                                              type: 'GET',
                                                                              username: 'logout'
                                                                              });
                                                                              } else if (bowser.webkit) {
                                                                              var xmlhttp = new XMLHttpRequest();
                                                                              xmlhttp.open("GET", secUrl, true);
                                                                              xmlhttp.setRequestHeader("Authorization", "Basic logout");
                                                                              xmlhttp.send();
                                                                              } else {
                                                                              alert("Logging out automatically is unsupported for " + bowser.name
                                                                              + "nYou must close the browser to log out.");
                                                                              }
                                                                              setTimeout(function () {
                                                                              window.location.href = redirUrl;
                                                                              }, 200);
                                                                              }






                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited Sep 20 at 8:38









                                                                              jwg

                                                                              3,20512951




                                                                              3,20512951










                                                                              answered Jan 9 '17 at 10:29









                                                                              Hasan Junaid Hashmi

                                                                              372




                                                                              372

















                                                                                  protected by Community Aug 3 '17 at 16:52



                                                                                  Thank you for your interest in this question.
                                                                                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                  Would you like to answer one of these unanswered questions instead?



                                                                                  這個網誌中的熱門文章

                                                                                  Tangent Lines Diagram Along Smooth Curve

                                                                                  Yusuf al-Mu'taman ibn Hud

                                                                                  Zucchini