简体   繁体   中英

php redirect to another page after validation

I am trying to figure out how to redirect after validation of a form (ie after conditions for my form have been met)(I have the header at the end of the PHP code). I have a basic form ,and I know this should be a straightforward code of line but I can't seem to make it work! Your advice is very much appreciated!

<?php

   $firstNameErr = '';
   $lastNameErr = '';
   $emailErr='';
   $passwordErr = '';
   $passwordConfErr='';


   if($_SERVER["REQUEST_METHOD"] == "POST"){
      $firstName = $_POST["firstName"];
      
      if(empty($firstName)){
         $firstNameErr =  "First Name is required";
      }

      else if(!preg_match("/^[a-zA-Z]+$/", $firstName)){
         $firstNameErr= "Only letters, no spaces or special characters allowed";
      }
      else{
         $firstNameErr = "Valid";
      }
   }

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

      if(empty($lastName)){
         $lastNameErr = "Last Name is required";
      }

      else if(!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $lastName)){
         $lastNameErr = "No Special characters or numbers allowed";
      }

      else{
         $lastNameErr = "Valid";
      }
   }

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

      if(empty($email)){
         $emailErr = "Email is required";
      }

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

      else{
         $emailErr = "Valid";
      }

   }

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


      if(empty($password)){
         $passwordErr = "Please Enter your password";

      }

      else if (strlen($password) < "8") {
         $passwordErr = "Your Password Must Contain At Least 8 Digits !";
      }
      else if(!preg_match("#[0-9]+#",$password)) {
         $passwordErr = "Your Password Must Contain At Least 1 Number !";
      }
      else if(!preg_match("#[A-Z]+#",$password)) {
         $passwordErr = "Your Password Must Contain At Least 1 Capital Letter !";
      }
      else if(!preg_match("#[a-z]+#",$password)) {
         $passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter !";
      }
      else if(!preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $password)) {
         $passwordErr = "Your Password Must Contain At Least 1 Special Character !";
      }
      else{
         $passwordErr = "Valid";
      }


   }

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

   }

   if($_SERVER["REQUEST_METHOD"] == "POST"){
      $confirmPassword = $_POST["confirmPassword"];
      $password = $_POST["password"];
      if(empty($confirmPassword)){
         $passwordConfErr = "Please Enter your password";

      }
      else if($password!=$confirmPassword){
         $passwordConfErr = "Passwords do not match";
      }
      else{
         $passwordConfErr="Valid";
      }

   }

   else{
      echo "Form not submitted with POST";
   }

   if($_SERVER["REQUEST_METHOD"] == "POST"){
      if(isset($_POST['Register']) and $firstNameErr == "Valid" and $lastNameErr =="Valid" and $emailErr == "Valid" and $passwordErr == "Valid" and $passwordConfErr=="Valid") {

         header("Location: profile.php");
         exit();

      }
   }

A single if ($_SERVER["REQUEST_METHOD"] == "POST"){ which wraps all $_POST logic would suffice, then depending on your app (if its mostly AJAX) you should use a response/request flow so the POST logic is at the top and it falls through to the view with the errors which can then be used in the view, or you should return JSON and do an AJAX request, else you won't be able to pick up the errors unless you put them into the session and then pick them up on redirect which is just extra steps.

Example request/response, for a single page ie register.php , this could be broken out where you load the HTML via an include or view loader but the idea is the same.

<?php
$errors = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // first name
    if (empty($_POST["firstName"])){
        $errors['firstName'] = "First Name is required";
    } else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
        $errors['firstName'] = "Only letters, no spaces or special characters allowed";
    }

     // last name
    if (empty($_POST["lastName"])) {
        $errors['lastName'] = "Last Name is required";
    } else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
        $errors['lastName'] = "No Special characters or numbers allowed";
    }

    // ...others

   
    // errors is empty, so must all be valid
    if (empty($errors)) {
        
        // do something like insert into db and set session status
        
        header("Location: profile.php");
        exit();
    }
    
    // otherwise continue to form
} ?>

<form>
    ...
    <input name="firstName" value="<?= htmlspecialchars($_POST['firstName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
    <?= isset($errors['firstName']) ? '<span class="form-error">'.$errors['firstName'].'</span>' : '' ?>
    
    <input name="lastName" value="<?= htmlspecialchars($_POST['lastName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
    <?= isset($errors['lastName']) ? '<span class="form-error">'.$errors['lastName'].'</span>' : '' ?>
</form>

Or if your going to use mostly AJAX, another way would be to return JSON, then you can access the errors to then build out the dom from the AJAX response.

<?php
// 
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    
    // set json response header
    header('Content-type: application/json;charset=utf-8');
    
    // Is POST
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        //
        $errors = [];
    
        // first name
        if (empty($_POST["firstName"])){
            $errors['firstName'] = "First Name is required";
        } else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
            $errors['firstName'] = "Only letters, no spaces or special characters allowed";
        }
    
         // last name
        if (empty($_POST["lastName"])) {
            $errors['lastName'] = "Last Name is required";
        } else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
            $errors['lastName'] = "No Special characters or numbers allowed";
        }
    
        // ...others
    
       
        // errors is empty, so must all be valid
        if (empty($errors)) {
            
            // do something like insert into db and set session status
            
            echo json_encode(['status' => 200]);
            exit();
        }

        echo json_encode(['errors' => $errors]);
        exit();
    } else {
        header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
        echo json_encode(['status' => 405]);
    }
} else {
    header('Location: /');
}

In both examples, use a single errors array then its easy to access and all in one place. You also don't need to set additional vars from the $_POST['...'] vars to validate them.

Your validating code should look like this:

$Name = $Surname = $username = $password = $confirm_password = 
$email ="";

if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Validate Name.   
    if (empty(trim($_POST["firstName"]))) {
        $errors[] = 'name required.';
    } else {
        $Name  = $_POST["firstName"];
    }
    // Validate lastName.   
    if (empty(trim($_POST["lastName"]))) {
        $errors[] = 'surname required.';
    } else {
        $Surname  = $_POST["lastName"];
    }

    // Validate username
    if (!preg_match("/^[a-zA-Z]+$/", $_POST["username"])) {
       $errors['username'] = "Only letters, no spaces or special characters allowed";
    }
    // Validate username from database to see if username already exist.
    //You can check for the email is well.
    if(empty(trim($_POST["username"]))){
        $errors[] = "Please enter a username.";
    } else{
        // Prepare a select statement
        $sql = "SELECT id FROM users WHERE username = :username";
        
        if($stmt = $pdo->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
            
            // Set parameters
            $param_username = trim($_POST["username"]);
            
            // Attempt to execute the prepared statement
            if($stmt->execute()){
                if($stmt->rowCount() == 1){
                    $errors[] = "This username is already taken.";
                } else{
                    $username = trim($_POST["username"]);
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            $stmt->closeCursor();
        }
    }
    
    // Validate password
    if(empty(trim($_POST["password"]))){
        $errors[] = "Enter password.";     
    } elseif(strlen(trim($_POST["password"])) < 6){
        $errors[] = "password should be min 6 characters.";
    } else{
        $password = trim($_POST["password"]);
    }    
    // Validate confirm password
    if(empty(trim($_POST["confirm_password"]))){
        $errors[] = "confirm pass.";     
    } else{
        $confirm_password = trim($_POST["confirm_password"]);
        if($password != $confirm_password){
            $errors[] = "pass no matches.";
        }
    }
    
    // Validate Email
    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
        $email = $_POST["email"];
    } else {
        $errors[] = "invalid email type.";
    }
    // Validate Email
    if(empty(trim($_POST["email"]))){
        $errors[] = 'email required.';
    }else {
            $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    }   
    
    if(empty($errors)){
        //if no errors
        //Do everythin else in here 
        //Do insert query after you are done redirect to profile page 
       header("Location: profile.php");
       exit();
    }
}

To get eroors :

<?php if(isset($errors)) {?>
<div class="error">
  <?php echo implode('<br/>', $errors); ?>
</div>  
<?php } unset($_SESSION['errors']); ?>

And your html form here if its in same page :

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> 
   //inputs etc..
</form>

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