php форма регистрации не выполняет проверку длины пароля правильно - PullRequest
1 голос
/ 09 февраля 2020

Я пытаюсь выполнить некоторые проверки в форме регистрации пользователя, используя HTML и PHP. Я попытался добавить один, который проверяет длину символов имени пользователя, который был введен. Когда я запускаю скрипт, я сталкиваюсь с ошибкой правильного URL: http://localhost:8888/PRCO304/signup.php?error=invalidlengthuname=ttttttt, однако я не получаю сообщение html, которое должно быть возвращено пользователю на странице регистрации. php. `Что должно быть: " Имя пользователя должно содержать не менее 8 символов! "

scripts / signup-script. php:

<?php
// Checking whether the user got to this page by clicking the proper signup button.
if (isset($_POST['signup-submit'])) {

  require 'db.php';

  $firstName = $_POST['first-name'];
  $lastName = $_POST['last-name'];
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password = $_POST['pwd'];
  $passwordRepeat = $_POST['pwd-repeat'];


  // We check for any empty inputs. 
  if (empty($firstName) || empty($lastName) || empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
    header("Location: ../signup.php?error=emptyfields&uname=".$username."&mail=".$email);
    exit();
  }
  // We check for an invalid username AND invalid e-mail.
  else if (!preg_match("/^[a-zA-Z0-9]*$/", $username) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header("Location: ../signup.php?error=invalidunamemail");
    exit();
  }
  // We check for an invalid username. In this case ONLY letters and numbers.
  else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
    header("Location: ../signup.php?error=invaliduname&mail=".$email);
    exit();
  }
  // We check for minimum amount of characters in username.
  else if (strlen($username <= 7)) {
    header("Location: ../signup.php?error=invalidlengthuname=".$username);
    exit();
  }
  // We check for an invalid e-mail.
  else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header("Location: ../signup.php?error=invalidmail&uname=".$username);
    exit();
  }
  // We check if the repeated password is NOT the same.
  else if ($password !== $passwordRepeat) {
    header("Location: ../signup.php?error=passwordcheck&uname=".$username."&mail=".$email);
    exit();
  }
  else {

    $sql = "SELECT username FROM student WHERE username = ?;";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
      // If there is an error we send the user back to the signup page.
      header("Location: ../signup.php?error=sqlerror");
      exit();
    }
    else {
      mysqli_stmt_bind_param($stmt, "s", $username);
      // Then we execute the prepared statement and send it to the database!
      mysqli_stmt_execute($stmt);
      // Then we store the result from the statement.
      mysqli_stmt_store_result($stmt);
      // Then we get the number of result we received from our statement. This tells us whether the username already exists or not!
      $resultCount = mysqli_stmt_num_rows($stmt);
      // Then we close the prepared statement!
      mysqli_stmt_close($stmt);
      // Here we check if the username exists.
      if ($resultCount > 0) {
        header("Location: ../signup.php?error=usertaken&mail=".$email);
        exit();
      }
      else {
        $sql = "INSERT INTO student (firstName, lastName, username, email, pwd) VALUES (?, ?, ?, ?, ?);";
        // Here we initialize a new statement using the connection from the db.php file.
        $stmt = mysqli_stmt_init($conn);
        // Then we prepare our SQL statement AND check if there are any errors with it.
        if (!mysqli_stmt_prepare($stmt, $sql)) {
          // If there is an error we send the user back to the signup page.
          header("Location: ../signup.php?error=sqlerror");
          exit();
        }
        else {

          // If there is no error then we continue the script!

          $hashedPwd = password_hash($password, PASSWORD_DEFAULT);

          mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);

          mysqli_stmt_execute($stmt);

          header("Location: ../signup.php?signup=success");
          exit();

        }
      }
    }
  }

  mysqli_stmt_close($stmt);
  mysqli_close($conn);
}
else {
  // If the user tries to access this page an inproper way, we send them back to the signup page.
  header("Location: ../signup.php");
  exit();
}

регистрация. php:

<?php
    // The index homepage includes the header
    require 'header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Homepage</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta charset="utf-8">

    <!-- CSS STYLING --> 
    <link href="./style.css" type="text/css" rel="stylesheet">
</head>

<body>

    <!-- The start of my Foldy Grids -->
    <section id="content">
            <div class="container">
                <section id="grid" class="clearfix">
                    <div class="cf show-grid">
                      <div class="row">
                        <div class="grid-1">grid-1</div>
                        <div class="grid-4">
            <?php

                // Here we create an error messages if the user made an error trying to sign up.
                if (isset($_GET["error"])) {
                if ($_GET["error"] == "emptyfields") {
                    echo '<p class="signuperror">Fill in all fields!</p>';
                }
                else if ($_GET["error"] == "invalidunamedmail") {
                    echo '<p class="signuperror">Invalid username and email!</p>';
                }
                else if ($_GET["error"] == "invaliduname") {
                    echo '<p class="signuperror">Invalid username!</p>';
                }
                else if ($_GET["error"] == "invalidmail") {
                    echo '<p class="signuperror">Invalid email!</p>';
                }
                else if ($_GET["error"] == "passwordcheck") {
                    echo '<p class="signuperror">Your passwords do not match!</p>';
                }
                else if ($_GET["error"] == "usertaken") {
                    echo '<p class="signuperror">Username is already taken!</p>';
                }
                else if ($_GET["error"] == "invalidlengthuname") {
                    echo '<p class="signuperror">Username must be at least 8 characters long!</p>';
                }
                }
                // Here we create a success message if the new user was created.
                else if (isset($_GET["signup"])) {
                if ($_GET["signup"] == "success") {
                    echo '<p class="signupsuccess">Signup successful!</p>';
                    }
                }
            ?>
                        <form action="scripts/signup-script.php" method="post">

                            <div class="signupContainer">
                                <h1>Sign Up</h1>
                                <p>Please fill in this form to create an account.</p>
                                <hr>
                            <?php
                                if (!empty($_GET["first-name"])) {
                                    echo '<label for="first-name"><b>First Name</b></label>
                                    <input type="text" placeholder="First Name" name="first-name" value="'.$_GET["first-name"].'">';
                                } else {
                                    echo '<label for="first-name"><b>First Name</b></label>
                                    <input type="text" placeholder="First Name" name="first-name">';
                                }
                                if (!empty($_GET["last-name"])) {
                                    echo '<label for="last-name"><b>Last Name</b></label>
                                    <input type="text" placeholder="Last Name" name="last-name" value="'.$_GET["last-name"].'">';
                                } else {
                                    echo '<label for="last-name"><b>Last Name</b></label>
                                    <input type="text" placeholder="Please Enter Last Name" name="last-name">';
                                }
                                if (!empty($_GET["username"])) {
                                    echo '<label for="username"><b>Username</b></label>
                                    <input type="text" placeholder="Username" name="username" value="'.$_GET["username"].'">';
                                } else{
                                    echo '<label for="username"><b>Username</b></label>
                                    <input type="text" placeholder="Username" name="username">';
                                }
                                if (!empty($_GET["email"])) {
                                    echo '<label for="email"><b>Email</b></label>
                                    <input type="text" placeholder="Email" name="email" value="'.$_GET["email"].'">';
                                } else {
                                    echo '<label for="email"><b>Email</b></label>
                                    <input type="text" placeholder="Email" name="email">';
                                }
                            ?>
                                <label for="pwd"><b>Password</b></label>
                                <input type="password" placeholder="Password" name="pwd">

                                <label for="pwd-repeat"><b>Repeat Password</b></label>
                                <input type="password" placeholder="Repeat Password" name="pwd-repeat">

                                <label>
                                <input type="checkbox" checked="checked" name="remember"> Remember me
                                </label>

                                <p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>

                                <div class="clearfix">
                                <button type="submit" class="signupBtn" name="signup-submit">Sign Up</button>
                                </div>
                            </div>
                        </form>

                        </div>
                        <div class="grid-1">grid-1</div>

                        </div>
                    </div>
                </section>
            </div>
        </section>
        <!-- The end of my Foldy Grids above -->
    </body>

    </html>
    <?php
        require 'footer.php';
    ?>

Ответы [ 2 ]

2 голосов
/ 09 февраля 2020

Исправлено if (strlen($username < 7)) { Вам может понадобиться поставить! (не) перед strlen.

Для меня ваши коды должны выглядеть следующим образом.

UPDATE должен был указать второй параметр в URL &uname= и исправить некоторое значение double проверяет ваши коды и проверяет работоспособность:

$error '';
if (isset($_POST['signup-submit'])) {

  require 'db.php';

  $firstName = $_POST['first-name'];
  $lastName = $_POST['last-name'];
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password = $_POST['pwd'];
  $passwordRepeat = $_POST['pwd-repeat'];


  // We check for any empty inputs. 
  if (empty($firstName) || empty($lastName) || empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
    $error = 'error';
    header("Location: ../signup.php?error=emptyfields&uname=".$username."&mail=".$email);
    exit();
  }
  // We check for an invalid username. In this case ONLY letters and numbers.
  if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
    $error = 'error';
    header("Location: ../signup.php?error=invaliduname&uname=".$username);
    exit();
  }
  // We check for minimum amount of characters in username.
  if(strlen($username) < 8){
    $error = 'error';
    header("Location: ../signup.php?error=lenuname&uname=".$username);
    exit();
  }
  // We check for an invalid e-mail.
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = 'error';
    header("Location: ../signup.php?error=invalidmail&mail=".$email);
    exit();
  }
  // We check if the repeated password is NOT the same.
  if ($password !== $passwordRepeat) {
    $error = 'error';
    header("Location: ../signup.php?error=passwordcheck&password=".$passwordRepeat);
    exit();
  }
  if(empty($error)){
    $sql = "INSERT INTO student (firstName, lastName, username, email, pwd) VALUES (?, ?, ?, ?, ?);";
    // Here we initialize a new statement using the connection from the db.php file.
    $stmt = mysqli_stmt_init($conn);
    // Then we prepare our SQL statement AND check if there are any errors with it.
    if (!mysqli_stmt_prepare($stmt, $sql)) {
      // If there is an error we send the user back to the signup page.
      header("Location: ../signup.php?error=sqlerror");
      exit();
    }else {

      // If there is no error then we continue the script!

      $hashedPwd = password_hash($password, PASSWORD_DEFAULT);

      mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);

      mysqli_stmt_execute($stmt);

      header("Location: ../signup.php?signup=success");
      exit();

    }
  }
}

Ваш signup.php

<?php

    // Here we create an error messages if the user made an error trying to sign up.
    if (isset($_GET["error"])) {
        if ($_GET["error"] == "emptyfields") {
            echo '<p class="signuperror">Fill in all fields!</p>';
        }
        if ($_GET["error"] == "invalidunamedmail") {
            echo '<p class="signuperror">Invalid username and email!</p>';
        }
        if ($_GET["error"] == "invaliduname") {
            echo '<p class="signuperror">Invalid username!</p>';
        }
        if ($_GET["error"] == "invalidmail") {
            echo '<p class="signuperror">Invalid email!</p>';
        }
        if ($_GET["error"] == "passwordcheck") {
            echo '<p class="signuperror">Your passwords do not match!</p>';
        }
        if ($_GET["error"] == "usertaken") {
            echo '<p class="signuperror">Username is already taken!</p>';
        }
        if ($_GET["error"] == "lenuname") {
            echo '<p class="signuperror">Username must be at least 8 characters long!</p>';
        }
    }
    // Here we create a success message if the new user was created.
    if (isset($_GET["signup"])) {
        if ($_GET["signup"] == "success") {
            echo '<p class="signupsuccess">Signup successful!</p>';
            }
    }
?>
<form action="scripts/signup-script.php" method="post">

    <div class="signupContainer">
        <h1>Sign Up</h1>
        <p>Please fill in this form to create an account.</p>
        <hr>
    <?php
        if (!empty($_GET["first-name"])) {
            echo '<label for="first-name"><b>First Name</b></label>
            <input type="text" placeholder="First Name" name="first-name" value="'.$_GET["first-name"].'">';
        } else {
            echo '<label for="first-name"><b>First Name</b></label>
            <input type="text" placeholder="First Name" name="first-name">';
        }
        if (!empty($_GET["last-name"])) {
            echo '<label for="last-name"><b>Last Name</b></label>
            <input type="text" placeholder="Last Name" name="last-name" value="'.$_GET["last-name"].'">';
        } else {
            echo '<label for="last-name"><b>Last Name</b></label>
            <input type="text" placeholder="Please Enter Last Name" name="last-name">';
        }
        if (!empty($_GET["username"])) {
            echo '<label for="username"><b>Username</b></label>
            <input type="text" placeholder="Username" name="username" value="'.$_GET["username"].'">';
        } else{
            echo '<label for="username"><b>Username</b></label>
            <input type="text" placeholder="Username" name="username">';
        }
        if (!empty($_GET["email"])) {
            echo '<label for="email"><b>Email</b></label>
            <input type="text" placeholder="Email" name="email" value="'.$_GET["email"].'">';
        } else {
            echo '<label for="email"><b>Email</b></label>
            <input type="text" placeholder="Email" name="email">';
        }
    ?>
        <label for="pwd"><b>Password</b></label>
        <input type="password" placeholder="Password" name="pwd">

        <label for="pwd-repeat"><b>Repeat Password</b></label>
        <input type="password" placeholder="Repeat Password" name="pwd-repeat">

        <label>
        <input type="checkbox" checked="checked" name="remember"> Remember me
        </label>

        <p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>

        <div class="clearfix">
        <button type="submit" class="signupBtn" name="signup-submit">Sign Up</button>
        </div>
    </div>
</form>

Смотрите скриншот

enter image description here

1 голос
/ 09 февраля 2020

Очень просто с моей точки зрения:

В URL вы ожидаете, что параметр error вернет invalidlengthuname

Значение $_GET['error'] = 'invalidlengthuname', хотя, как я вижу в вашем Например, в вашем перенаправлении значение $_GET['error'] равно invalidlengthuname=ttttttt.

. Вы должны удалить второй = вместе с "ttttttt" или создать второй параметр URL, чтобы вы могли отслеживать, какое имя пользователя Пользователь опубликовал: ?error=invalidlengthuname&input=ttttttt. Обратите внимание на знак &.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...