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

Asked

Viewed 5,307 times

4

In PHP, I usually work on user authentication in a restricted area using the variable $_SESSION, but I want to change this method to cookies so that the session does not end when closing the browser. On sites like Google and Facebook, the user is logged in and back in 30 days for example, the session is still active.

The code I’m using:

php authenticates.

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;

On 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 above code expires. I also believe that you are very insecure.

  • 3

    What do you want to store in cookies? Session usage already implies the use of a cookie (which stores the session id).

  • There must be some reason behind this change, right? Scalability? Performance? Perhaps it is best to rephrase the question to make clear what you want to do. This should attract quality answers.

  • Actually I just want the session to last longer, for example: 30 days. In the case of the $_SESSION variable if I close the browser the session expires. This can be done only with cookie or I’m wrong?

  • 1

    I don’t know how you’re authenticating users or how you’re logging in, but I do $_SESSION Many years and the session only expires if the user logout, clear the cookies the page in question or the server administrator cleans the session files, otherwise it is years and still active. That said, it would be nice to see your code so we can review it and provide the help you need.

  • Actually Anderson, in the case of facebook is used many things besides cookie. In your case it is interesting to use the cookie to store a $_SESSION value to prevent it from being destroyed. There are some methods to do this with $_SESSION + Cookies.

1 answer

2


You can replace the code-based session management functions that store session data in cookies. Here you use the function session_set_save_handler to replace the functions.

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

This method has the advantage of not only allowing sessions to last longer than the time the browser stays open, but also allowing your session application to run in a relaxed environment with multiple clustered web servers.

However, it is not much recommending when you want to store a lot of data in sessions because it increases the size of the cookie and this makes it take the browser to access the server.

Cookies also have a size limit of 4KB, so session data cannot exceed this size.

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

  • 1

    I was unaware of this solution mlemos. I ran the tests using the same code I posted above and it worked perfectly. Thank you for sharing your knowledge.

  • 1

    Opa @Anderson glad you solved. No need to thank. Share your knowledge to reciprocate.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.