How to make a Session

Asked

Viewed 265 times

1

I have a system that has a login page, but it only sees if there is that email and password that the user typed in the database and releases to the main page.

Now I needed to create a profile page for this user so the system needs to know more than it has a logged in user, but yes which user is logged in to play his information on a profile page.

These are two things I don’t know: make the system recognize which user is logged in and put this information on a profile page.

This is my login page:

            <section id="hello" class="home bg-mega">
                <div class="overlay"></div>
                <div class="container">
                    <div class="row">
                        <div class="main_home">
                            <div class="home_text">
                                <h1 class="text-white">INTYME <br/> LOGIN</h1>
                            </div>
                            <form method="post" action="validacao.php" style=" 
                            background-color: #7a494994;
                            padding-bottom: 20px;
                            padding-top: 20px;
                            padding-left: 10px;
                            padding-right: 10px;"
                            >
                                <div class="form-group">
                                    <label style="color:#ffffff">Email</label>
                                    <input type="text" class="form-control" id="EMAIL" name="EMAIL"  placeholder="Insira aqui o seu e-mail">
                                </div>
                                <div class="form-group">
                                    <label style="color:#ffffff">Senha</label>
                                    <input type="password" class="form-control" id="SENHA" name="SENHA"  placeholder="Insira aqui a sua senha">
                                </div>
                                    <a href="inicial.php" class="btn btn-primary m-top-20">Entrar</a>
                                    <a href="cadastro.php" class="btn btn-primary m-top-20">Cadastre-se</a>
                            </form>
                        </div>
                    </div>
                </div>
            </section> 

This is my login validation page:

<?php
//Esse login ficou meio complicadinho, então vou deixar comentado: 
ini_set('display_errors', true);
error_reporting(E_ALL);
// Primeiro verifica se o post não está vazio
if (!empty($_POST) AND !empty($_POST['EMAIL']) OR !empty($_POST['SENHA'])) {
    $link = mysql_connect('localhost', 'root', '');
    mysql_select_db('intyme');
    // Tenta se conectar a um banco de dados MySQL
    $email = mysql_real_escape_string($_POST['EMAIL']);
    $senha = mysql_real_escape_string($_POST['SENHA']);
    $ativo = mysql_real_escape_string($_POST['ATIVO']);
    //$senha = md5($senha);

    $sql = "SELECT `ID`, `EMAIL`, `SENHA`, `ATIVO`  FROM `usuarios` WHERE (`EMAIL` = '". $email ."') AND (`SENHA` = '". $senha ."')";
    $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 "Login inválido!"; exit;
    } else {
      $resultado = mysql_fetch_assoc($query);
      // Verifica se o usuário é 0 ou 1

      if ($resultado['ativo'] == 0) { header("Location: inicial.php"); } 
      else { header("Location: inicial.php"); }

      exit;
    }
}
?>
  • What is the session and PDO relationship you refer to? They are separate things.

  • You need to store the user ID in the session and then use that ID to make a select bringing the information relating to that user.

  • 1

    I strongly advise to use password_hash and password_verify not to keep passwords clear in the bank and avoid compromising them in situations of gaps. As an aside, if and else redirecting to the same page header("Location: inicial.php"); doesn’t make sense

  • Ah, they’re redirecting to the same page because I logged in with permission, but I still don’t have a ADM page so I’ve got them both redirecting to the same place for now.

1 answer

2


Just add a line here:

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 "Login inválido!"; exit;
} else {
  $resultado = mysql_fetch_assoc($query);
  // Verifica se o usuário é 0 ou 1

  $_SESSION["login"] = $resultado["id"] //Cria uma sessão com o id do usuário

  if ($resultado['ativo'] == 0) { header("Location: inicial.php"); } 
  else { header("Location: inicial.php"); }

  exit;
}

Then when you need it, just fetch the user’s data logged in by id

To use sessions it is necessary to call session_start(), I suggest you do this in the first line of php:

<?php
session_start();
//...

Read more on documentation

  • So, I went to try to go use this session_start(); on my profile page and give a quote $_SESSION['EMAIL'] for example, but nothing showed up. Can you tell me why?

  • You called session_start() on all pages that is used sessions?

  • Yes, I did call.

  • 1

    Place session_start() in the first line, if not placed. Then check if when created the session with email the value of the variable email was not empty

  • Guys, the error was in the page that I log in and not in Sesssion, Sesssion was working perfectly.

Browser other questions tagged

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