[HOWTO] How to force .htaccess deauthentication through PHP

By | February 25, 2011

So you decided to use .htaccess authentication for your site. And now you’re wondering how to create a logout page? According to Apache, you can’t. They send the ball to browsers, who apparently don’t want to support such a feature. There are few workarounds, but all of them seemed odd. Most people were suggesting sending bad user/pass to force re-auth, but browsers can remember more than one user/pass combination, so that wasn’t a good enough solution either.

However, that was a step in the right direction. The trick is not to send junk information, but to tell the browser it failed auth, even if it didn’t. The code below does exactly that. Thanks to whoever wrote it. Create a logout.php page, and add this to it:



if ($_SESSION[“logout”]) {
$_SESSION[“logout”] = false;
header(‘Location: ./’); // Change index.php to your main page (if it’s not already).
} else {
header(‘HTTP/1.0 401 Unauthorised’);
header(‘WWW-Authenticate: Basic realm=”MyRealm”‘); // Change MyRealm to be the same as AuthName in .htaccess
$_SESSION[“logout”] = true;

// Set “escape” message here.
echo “Logged out.”;


That’s it. Tested on IE8 (don’t have 7 available), Firefox 3.6.13, Safari 5.0.3, Lynx 2.8.7, Opera 11.1, Konqueror 4.4.5. Only Konqueror fails. I never liked KDE anyway. Not tested on Chrome, feedback appreciated!


<Re-posted Jan 1st 2018>

Leave a Reply

Your email address will not be published. Required fields are marked *