简体   繁体   中英

How can I properly validate my registration form inputs with PHP functions?

I am a beginner with PHP and am trying to validate my registration form, but the preg_match functions and email filter function are not validating the input. The form submits and the values or inserted into my database and any input works without being validated. Here is my PHP:

<?php

// define errors
$firstnameErr = $lastnameErr = $usernameErr = $passwordErr = $emailaddressErr = "";




if ($_SERVER["REQUEST_METHOD"] == "POST") {


  if (empty($_POST["firstname"])) {
    $firstnameErr = "First Name is required";
  } else {
    $firstname = ($_POST["firstname"]);
    // name only contains letters and space
    if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
      $firstnameErr = "Only letters and white space allowed";
    }
  }
    if (empty($_POST["lastname"])) {
    $lastnameErr = "Last Name is required";
  } else {
    $lastname= ($_POST["lastname"]);
    // name only contains letters and space
    if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
      $lastnameErr = "Only letters and white space allowed";
    }
  }


 if (empty($_POST["emailaddress"])) {
    $emailaddressErr = "Email address is required";
  } else {
    $emailaddress = ($_POST["emailaddress"]);

    if (!filter_var($emailaddress, FILTER_VALIDATE_EMAIL)) {
      $emailaddressErr = "Invalid email format";
    }
  }


 if (empty($_POST["username"])) {
    $usernameErr = "A username is required";
  } else {
    $username = ($_POST["username"]);
  }



            if (empty($_POST["password"])) {
    $passwordErr = "A password is required";
  } else {

    $password = PASSWORD_HASH($_POST['password'], PASSWORD_DEFAULT);
        }

My HTML is below. I suppose the first name is validated client-side because of the regex, but I want it done server-side as well with preg_match. I'm not certain I'm doing this correctly.

<form style="display:flex"; name="signupform" action="registration.php" method="post">


              <div class="container">
                <div class ="row justify-content-center">
                    <div class ="col-md-6">
                        <h1>Registration</h1>
                        <hr class="mb-3">

                        <label for="firstname"><b>First Name</b></label>
                        <input class= "form-control" type="text" placeholder="Enter your First Name" name="firstname" required>
                        <span class="error">* <?php echo $firstnameErr;?></span>

                        <label for="lastname"><b>Last Name</b></label>
                        <input class= "form-control" type="text" placeholder="Enter your Last Name" name="lastname" required>
                        <span class="error">* <?php echo $lastnameErr;?></span>

                        <label for="emailaddress"><b>Email Address</b></label>
                        <input class= "form-control" type="text" placeholder="Enter your Email Address" name="emailaddress" required>
                        <span class="error">* <?php echo $emailaddressErr;?></span>


                        <label for="username"><b>Username</b></label>
                        <input class= "form-control" type="text" placeholder="Enter your desired username" name="username" required>
                        <span class="error">* <?php echo $usernameErr;?></span>

                        <label for="password"><b>Password</b></label>
                        <input class= "form-control" type="password" placeholder="Enter a password" name="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required>
                        <span class="error">* <?php echo $passwordErr;?></span>
                        <em> Password must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters</em><br>


                        <hr class ="mb-3">
                        <input class="btn btn-block btn-primary" type="submit" name="create" value="Sign Up">
                        <hr class = "mb-3">


                    </div>

                </div>
            </div>  
    </form>

Try something like this in your logic. Because your variables ($lastname, $emailaddress) are declared and filled with untested data in your code.

 if (empty($_POST["lastname"])) {
    $lastnameErr = "Last Name is required";
  } else {
    if (!preg_match("/^[a-zA-Z ]*$/",$_POST["lastname"])) {
      $lastnameErr = "Only letters and white space allowed";
    }else{
     /* if lastname valid then create $lastname */
     $lastname= $_POST["lastname"];
    }
  }
  if (empty($_POST["emailaddress"])) {
    $emailaddressErr = "Email address is required";
  } else {
    if (!filter_var($_POST["emailaddress"], FILTER_VALIDATE_EMAIL)) {
      $emailaddressErr = "Invalid email format";
    }else{
      // if email address valid then create $emailaddress
      $emailaddress = ($_POST["emailaddress"]);
    }
  }

So before calling your function to store the datas in your database, just check if the variables exist with a isset($lastname) && isset($emailaddress) ... Well I guess you got the idea.

And from what I read on the net, you shouldn't trust anything coming from the front-end, even with input validation, always double-check before inserting the datas in your database.

Good luck.

I simplified your code, hope this helps:)

<?php
//define errors
$error_message = "";

$firstname="";
$lastname="";
$emailaddress="";
$username="";
$password="";

if(isset($_POST['create']) && $_SERVER["REQUEST_METHOD"] == "POST"){

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$emailaddress = $_POST['emailaddress'];
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);


if(empty($firstname) || $firstname == ""){
$error_message = "First Name is required!";
}
elseif( !preg_match("/^[a-zA-Z ]*$/",$firstname) ){
$error_message = "Only letters and white space allowed!";
}
elseif(empty($lastname) || $lastname == ""){
$error_message = "Last Name is required!";
}
elseif( !preg_match("/^[a-zA-Z ]*$/",$lastname) ){
$error_message = "Only letters and white space allowed!";
}
elseif(empty($emailaddress) || $emailaddress == ""){
$error_message = "Email address is required!";
}
elseif(!filter_var($emailaddress, FILTER_VALIDATE_EMAIL)){
$error_message = "Invalid email format!";
}
elseif(empty($username) || $username == ""){
$error_message = "Username is required!";
}
elseif(empty($password) || $password == ""){
$error_message = "Password is required!";   
}
else{
//insert query
}

}

?>

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form style="display:flex"; name="signupform" action="" method="post">


          <div class="container">
            <div class ="row justify-content-center">
                <div class ="col-md-6">
                    <span class="error">* <?php echo $error_message;?></span>
                    <h1>Registration</h1>
                    <hr class="mb-3">

                    <label for="firstname"><b>First Name</b></label><br>
                    <input class= "form-control" type="text" placeholder="Enter your First Name" name="firstname" value="<?php echo $firstname; ?>"><br>


                    <label for="lastname"><b>Last Name</b></label><br>
                    <input class= "form-control" type="text" placeholder="Enter your Last Name" name="lastname" value="<?php echo $lastname; ?>"><br>


                    <label for="emailaddress"><b>Email Address</b></label><br>
                    <input class= "form-control" type="text" placeholder="Enter your Email Address" name="emailaddress" value="<?php echo $emailaddress; ?>"><br>


                    <label for="username"><b>Username</b></label><br>
                    <input class= "form-control" type="text" placeholder="Enter your desired username" name="username" value="<?php echo $username; ?>"><br>


                    <label for="password"><b>Password</b></label><br>
                    <input class= "form-control" type="password" placeholder="Enter a password" name="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" value="<?php echo $password; ?>"><br>

                    <em> Password must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters</em><br>


                    <hr class ="mb-3">
                    <input class="btn btn-block btn-primary" type="submit" name="create" value="Sign Up" style="cursor: pointer;">

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM