How to work a secure session in PHP using cookies so that the session does not expire when closing the browser?

4

In PHP, I usually work with restricted user authentication using the $_SESSION variable, however I want to change this method to cookies so that the session does not close when closing the browser. On sites like Google and Facebook, the user logs in and if they return in 30 days for example, the session is still active.

The code I'm using:

autentica.php

session_start();
// Verifica se houve POST e se o usuário ou a senha é(são) vazio(s)
if (!empty($_POST) AND (empty($_POST['usuario']) OR empty($_POST['senha']))) {
    header("Location: login.php"); exit;
}

$usuario = mysql_real_escape_string($_POST['usuario']);
$senha = mysql_real_escape_string($_POST['senha']);

// Validação do usuário/senha digitados
$sql = "SELECT * FROM 'usuarios' WHERE ('usuario' = '". $usuario ."') AND ('senha' = '". $senha ."')  LIMIT 1";
$query = mysql_query($sql);
if (mysql_num_rows($query) != 1) {
    // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
    echo '<script language="JavaScript">
       <!--
          alert("Dados Incorretos!\n\n");
          history.back();
          //-->
       </script>'; 
} else {
    // Salva os dados encontados na variável $resultado
    $resultado = mysql_fetch_assoc($query);

    // Se a sessão não existir, inicia uma
    if (!isset($_SESSION)) session_start();

    // Salva os dados encontrados na sessão
    $_SESSION['UsuarioID'] = $resultado['id'];
    // Redireciona o visitante

    header("Location: index.php"); exit;

In the restricted pages I use the following code:

if (!isset($_SESSION)) session_start();
if (!isset($_SESSION['UsuarioID'])) {
session_destroy();
header("Location: autentica.php"); exit;
}

When you close the browser the session created in the code above expires. I also think you are very insecure.

    
asked by anonymous 26.02.2014 / 21:03

1 answer

2

You can override session management functions with code that stores session data in cookies. Then use the session_set_save_handler function to replace the functions.

Here's a class for data storage in cookies that does just that. The class uses encryption so session data is not visible to browsers.

This method has the advantage of not only allowing sessions to last beyond the time the browser is open, but also allows your session application to work in an environment shared with multiple clustered Web servers.

However, it is not very recommendable when you want to store a lot of data in sessions because it increases the size of the cookie and this slows down browser access to the server.

Cookies also have a size limit of 4KB, so session data can not exceed that size.

A simpler method that can solve your problem is to set the duration of the session cookie and use the session_set_cookie_params function. and use a value other than 0 for the lifetime parameter.

    
27.02.2014 / 04:02