Best way to make a script to logout

3

I am developing a system in which it is accessed with the login and password, once logged in the user has the option to log out, below my script:

if(isset($_SESSION['logado'])){
    session_destroy();
    header("Location:index.php");
}

I want to know if this is a correct way to do this, since this code is in a separate file

Here is the button that logs out

echo " <a href='doLogout.php'>Sair</a>";
    
asked by anonymous 01.09.2014 / 05:14

2 answers

7

An additional problem with this Logout, in addition to what was already mentioned by @PapaCharlie, is that any link off to the logout page complicates the user experience. As it is, just an accidental click on the history or an autocomplete wrong and the guy is "escaping" the session "unlogging" inadvertently.

In addition, some malicious "competitor" could force your users to permanently lose their session with an invisible link on other sites (example: <script src="http://seusite/caminhodologout">).

Idealifthislogoutpageweretoreceiveaparameterthatwouldidentifythesession.Ifitdoes,itlogsout,ifitdoesnot,itshows"Confirm logout?" and in the SIM it uses a link with the parameter, so an "old" pro logout link would not work.

Simplified solution example:

Logout link:

echo '<a href="doLogout.php?token='.md5(session_id()).'">Sair</a>';
// sim, MD5 é seguro suficiente nesse contexto (e é apenas exemplo).

Logout page:

session_start();
$token = md5(session_id());
if(isset($_GET['token']) && $_GET['token'] === $token) {
   // limpe tudo que for necessário na saída.
   // Eu geralmente não destruo a seção, mas invalido os dados da mesma
   // para evitar algum "necromancer" recuperar dados. Mas simplifiquemos:
   session_destroy();
   header("location: http://exemplo.com.br/index.php");
   exit();
} else {
   echo '<a href="#">#                                    
01.09.2014 / 14:47
4

Usually login is a combination of sessions and cookies that guarantee the authenticity of the user even after the browser closes. Assuming a simple login system with single session use, you have 2 examples below. Be sure to call the session_start function at the right time.

1) If you have a page just for logout, you can just use it this way:

session_start();
session_destroy();
header("location: http://www.dominio.com.br/index.php"); 

2) If your application differs from the example above, you can use:

session_start(); // previamente chamada 

Removing sessions

if(isset($_SESSION['logado'])){
    // se você possui algum cookie relacionado com o login deve ser removido
    session_destroy();
    header("location: http://www.dominio.com.br/index.php");
    exit();
}
    
01.09.2014 / 05:36