-2

I've got this code and it has gone bad. Im kinda new to php and mysql interactions and I really cant see the problem here. My goal is to display the 'nome' session variable to another page, connecting server.php to principal.php.

'nome' session variable does not show up on principal.php, even though i sessioned it on server.php. 'succcess' works for some reason, nevertheless.

server.php

session_start();

//inicializando variaveis

$nome = "";
$email = "";
$senha = "";
$errors = array();

//conectando ao banco

$db = mysqli_connect('localhost', 'root', '', 'myguider');

//registrando usuario

if (isset ($_POST['registrar'])) {

    //recebendo todos os valores dos inputs

    $nome = mysqli_real_escape_string($db, $_POST['nome']);
    $email = mysqli_real_escape_string($db, $_POST['email']);
    $senha = mysqli_real_escape_string($db, $_POST['senha']);
    $confirmasenha = mysqli_real_escape_string($db, $_POST['confirmasenha']);
    $endereco = mysqli_real_escape_string($db, $_POST['endereco']);
    $cidade = mysqli_real_escape_string($db, $_POST['cidade']);
    $bairro = mysqli_real_escape_string($db, $_POST['bairro']);
    $estado = mysqli_real_escape_string($db, $_POST['estado']);
    $graudif = mysqli_real_escape_string($db, $_POST['graudificuldade']);

    //garantindo que o formulario ta preenchido
    //adicionando os erros correspondentes para a array de erros

    if(empty($nome)) {array_push($errors, "Digite o seu nome.");}
    if(empty($email)) {array_push($errors, "Digite o seu e-mail.");}
    if(empty($senha)) {array_push($errors, "Digite sua senha.");}
    if(empty($endereco)) {array_push($errors, "Informe o CEP.");}
    if(empty($cidade)) {array_push($errors, "Informe o CEP.");}
    if(empty($bairro)) {array_push($errors, "Informe o CEP.");}
    if(empty($estado)) {array_push($errors, "Informe o CEP.");}
    if(empty($graudif)) {array_push($errors, "Informe o grau de dificuldade.");}

    if($senha != $confirmasenha){
        array_push($errors, "As senhas não coincidem");
    }


//checar no banco pra ter ctz de que nao havera usuarios iguais

   $query_checar_usuario = "SELECT * FROM tb_cliente WHERE nm_cliente='$nome' OR nm_cliente='$email' LIMIT 1";
   $resultado = mysqli_query($db, $query_checar_usuario);
   $usuario = mysqli_fetch_assoc($resultado);

if ($usuario) { //se usuario existir
    if($usuario['nome'] === $nome){
        array_push($errors, "Nome já cadastrado no sistema.");
    }

    if($usuario['email'] === $email){
        array_push($errors, "E-mail já cadastrado no sistema.");
    }
  }

  //Registra o usuário se não há erros no formulário
  if(count($errors) == 0){

    $senhacrypt = md5($senha); //cryptando a senha

    $query = "INSERT INTO tb_cliente (nm_cliente, ds_email, ds_senha, ic_grau_dificuldade, ds_endereco, nm_bairro, nm_cidade, nm_estado)
    VALUES('$nome', '$email', '$senha', '$graudif', '$endereco', '$bairro', '$cidade', '$estado')";

    mysqli_query($db, $query);

    $_SESSION['nome'] = $nome;
    $_SESSION['success'] = "Você está logado!";
    header('location: principal.php');
   }
}

if (isset($_POST['logar'])) {
    $email = mysqli_real_escape_string($db, $_POST['email']);
    $senha = mysqli_real_escape_string($db, $_POST['senha']);
    $nome = mysqli_real_escape_string($db, $_POST['nome']);
  
    if (empty($email)) {
        array_push($errors, "Por favor, digite seu e-mail.");
    }
    if (empty($senha)) {
        array_push($errors, "Por favor, digite sua senha.");
    }
  
    if (count($errors) == 0) {
        $senhacrypt = md5($senha);
        $query = "SELECT * FROM tb_cliente WHERE ds_email='$email' AND ds_senha='$senha'";
        if (mysqli_num_rows(mysqli_query($db, $query)) > 0) {

            $query = "SELECT nm_cliente FROM tb_cliente WHERE ds_email = '$email'";
            mysqli_query($db, $query);

          $_SESSION['nome'] = $nome;
          $_SESSION['email'] = $email;
          $_SESSION['success'] = "Você está logado!";
          header('location: principal.php');
        }else {
            array_push($errors, "Combinação errada de e-mail e senha");
        }
    }
  }
?>

principal.php

<?php

session_start();

  if (!isset($_SESSION['nome'])) {
    $_SESSION['msg'] = "Você precisa realizar o login primeiro.";
    header('location: login.php');
  }
  if (isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['nome']);
    header("location: login.php");
  }
?>
<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
    <link rel="stylesheet" href="cadastro.css">
</head>
<body>

<div class="header">
    <h2>Home Page</h2>
</div>
<div class="content">
    <!-- notification message -->
    <?php if (isset($_SESSION['success'])) : ?>
      <div class="error success">
        <h3>
          <?php 
            echo $_SESSION['success'];
          ?>
        </h3>
      </div>
    <?php endif ?>

    <!-- logged in user information -->
    <?php  if (isset($_SESSION['nome'])) : ?>
        <p>Bem vindo, <strong><?php echo $_SESSION['nome']; ?></strong></p>
        <p>Teste <?php echo $_SESSION['nome']; ?></p>
        <p> <a href="index.php?logout='1'" name="logout" style="color: red;">deslogar</a> </p>
    <?php endif ?>
</div>
        
</body>
</html>
  • 1
    You shouldn't rely on `mysqli_real_escape_string`. Instead, you should learn about [Prepared Statements](https://en.wikipedia.org/wiki/Prepared_statement) with [parameterized queries](https://stackoverflow.com/a/4712113/5827005). I recommend switching to `PDO` (Along with the opinion of many other PHP developers), which I [wrote a class for](https://github.com/GrumpyCrouton/GrumpyPDO) to make it extremely easy, clean, and more secure than using non-parameterized queries. Whether you use this class or not, I still recommend switching to `PDO`. – GrumpyCrouton Mar 08 '21 at 16:26
  • If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection – Dharman Mar 08 '21 at 16:28
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Mar 08 '21 at 16:28

1 Answers1

0

What is your code Even Doing ?

session_destroy();
unset($_SESSION['nome']);
header("location: login.php");

You are using unset and then You are trying to Echo the Session ?

Ryan The Ghost
  • 116
  • 1
  • 13