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.
What do you want to store in cookies? Session usage already implies the use of a cookie (which stores the session id).
– bfavaretto
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.
– utluiz
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?
– anderson
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.– Zuul
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.
– user5897