Question:

Direct logout link

Anna: 2 weeks ago

I know I can display the login/logout form with the following link:

http://example.com/index.php?option=com_users&view=login

But once logged in, this link will redirect the user to a page with a logout button that has to be clicked.

Is it possible to create a link that will log out the current user directly?

Answer:
Weston: 2 weeks ago

The following link is for direct logout:

http://example.com/index.php?option=com_users&task=user.logout

But a user token is required in order to avoid an error message Invalid Token, and some PHP magic is required in order to get the token. The following code will display a Login link to guests, and a direct Logout Username link to logged in users:

$user = JFactory::getUser();
if ($user->guest)
{
    echo '<a href="index.php?option=com_users&view=login">Login</a>';
}
else
{
    $userToken = JSession::getFormToken();
    echo '<a href="index.php?option=com_users&task=user.logout&' . $userToken . '=1">Logout '  . $user->username . '</a>.';
}

The code can be included in any extension, or using a plugin/module that allows inserting PHP code directly (e.g. DirectPHP (http://extensions.joomla.org/extensions/extension/core-enhancements/coding-a-scripts-integration/directphp), Custom HTML Advanced (http://extensions.joomla.org/extensions/extension/core-enhancements/coding-a-scripts-integration/custom-html-advanced), Sourcerer (http://extensions.joomla.org/extensions/extension/core-enhancements/coding-a-scripts-integration/sourcerer) or similar).