0

I'm creating a register for the user. If the user name already exists in the database the program needs to show a message. It works, but I don't know why the program does'nt show the message the first time. For example, if the name michael is already registered and I try to put again the message "user name already exists" is not displayed. But if I try again, then is displayed. Or if I try with another name already registered, is displayed. But not the first time, only the second and after. Could you help me please.

<?php
session_start();
if(!isset($_SESSION['$k'])) {
    $_SESSION['$k'] = false;
}
?>

<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="register.css">
    <title>Word Games Register</title>
</head>

<body>
    <form action="" method="POST">
        <a href="../index.php"><img src="../img/close.png" /></a>
        <h2>REGISTRARSE</h2>
        <input type="text" placeholder="Usuario" name="user">
        <input type="password" placeholder="Contraseña" name="password">
        <input type="text" placeholder="E-mail" name="email">
        <?php
            if($_SESSION['$k']) {
                echo '<h5 id="mensaje">El usuario ya existe</h5>';
                unset($_SESSION['$k']);
            }
        ?>
        <input type="submit" value="Enviar" name="btn">
    </form>
</body>
</html>

<?php
if(isset($_POST['btn'])){
    $user = $_POST['user'];
    $pass = $_POST['password'];
    $email = $_POST['email'];

    $link = mysqli_connect("localhost", "root", "") or die ("Error       conectando al servidor" . mysqli_error());
    mysqli_select_db($link, "wordgames") or die ("Error seleccionando la base de datos" . mysqli_error());
    mysqli_query($link, "SET NAMES 'utf8'");

    $resultado = mysqli_query($link, "select * from usuario where usuario='$user'") or die ("Error en la consulta" . mysqli_error());
    $filas = mysqli_num_rows($resultado);
    if($filas > 0){
        $_SESSION['$k'] = true;
    } else{
        mysqli_query($link, "insert into usuario values (NULL, '$user', '$pass', '$email')") or die ("Error en la consulta". mysqli_error());
        mysqli_close($link);
        header("location:../index.php");
    }


}
?>
Edward
  • 2,291
  • 2
  • 19
  • 33
user2558831
  • 83
  • 1
  • 8
  • you need to run an ajax call to check the database and update the user live. – DevDonkey Apr 29 '16 at 15:49
  • That would be fancy, but not strictly necessary. – Rick Apr 29 '16 at 16:03
  • Easy and common trouble. If you execute manualy your php in your mind, you'll see that, when you are in a POST context, you display the HTML first (so, no SESSION set), then parsing your $_POST to find there's already a user with your name and so, setting the SESSION to true. Then, nothing else, so your HTML is already built without your error message. The fact it appears when you refresh is just because it's stored in SESSION. Please, always do your PHP stuff BEFORE echoing any HTML text, and it will work. You also don't need SESSION to do that if you put your PHP part first. – niconoe Apr 29 '16 at 16:25
  • [Little Bobby](http://bobby-tables.com/) says [your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Apr 29 '16 at 16:45
  • **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure that you [don't escape passwords](http://stackoverflow.com/q/36628418/1011527) or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Apr 29 '16 at 16:45
  • If I put the PHP part first, with no SESSION, how can I display the message right in the place where I want it: between the input and the submit button. If the user exists I want to show the message in that particular place. That's why I've created that SESSION. Is it bad practice? Thanks – user2558831 Apr 29 '16 at 18:25

1 Answers1

2

You are checking if a certain session variable is set, and if so, you display your "User already exists" message. The point is that you set this variable after you have already printed everything, so basically you first check "Is it set?" and then you set it. As a result, your message is not printed (as that code is already evaluated).

As it is a session variable, it remains set during the session. Hence, if you reload the page, your message will show up. If you then try another existing user, the variable was already set previously, hence the message is shown (albeit basically for the previous username).

One way to fix this could be to move your lower PHP code block above your HTML; that way, your header("Location: ...") will also work.

Rick
  • 443
  • 2
  • 10