str_replace $ _POST数组中的变量值

时间:2016-09-23 20:30:56

标签: php str-replace

感谢您的时间。我目前正在参加在线PHP课程,并且正在尝试解决课程中未涉及的问题。 如果根据某些参数存在错误,则存在一种错误放置在数组中的形式。目前,当错误显示给用户时,它显示$ _POST值,但我想显示自定义错误消息。我目前正在尝试使用in_array和字符串替换,并且失败。我没有得到任何PHP错误。 谁知道我怎么做到这一点? 这是我的控制器和视图:

<?php
// add database connection script
include_once 'resource/database.php';
include_once 'resource/utilities.php';


// process the form if the reset password button is clicked
if(isset($_POST['passwordResetBtn'])) {
  // initialize an array to store any error message from the form
  $form_errors = array();

  // form validation
  $required_fields = array('email', 'new_password', 'confirm_password');

  // call the function to check empty fields and merge the return data into form_error array
  $form_errors = array_merge($form_errors, check_empty_fields($required_fields));

  // Fields that require checking for minimum length
  $fields_to_check_length = array('new_password' => 6, 'confirm_password' => 6);

  // call the function to check minimum required length and merge the return data into form_errors array
  $form_errors = array_merge($form_errors, check_min_length($fields_to_check_length));

  // email validation / merge the return data into the form_errors array
  $form_errors = array_merge($form_errors, check_email($_POST));

  // check if error array is empty, if yes process form data and insert record
  if(empty($form_errors)) {
    // collect form data and store in variables
    $email = $_POST['email'];
    $password1 = $_POST['new_password'];
    $password2 = $_POST['confirm_password'];



    // check if the new password and confirm password are the same
    if($password1 != $password2) {
      $result = "<p style='padding: 20px; border: 1px solid red; color: red;'>Passwords do not match, please do it over!</p>";
    } else {
      try {
        // create sql select statement to verify if email address input exists in the database
        $sqlQuery = "SELECT email FROM users WHERE email = :email";
        $statement = $db->prepare($sqlQuery);
        $statement->execute(array(':email' => $email));
        // check if record exists
        if($statement->rowCount() == 1) {
          // hash the password
          $hashed_password = password_hash($password1, PASSWORD_DEFAULT);
          // SQL statement to update password
          $sqlUpdate = "UPDATE users SET password = :password WHERE email = :email";
          // sanitize the statement
          $statement = $db->prepare($sqlUpdate);
          // execute statement
          $statement->execute(array(':password' => $hashed_password, ':email' => $email));
          $result = "<p style='padding: 20px; border: 1px solid green; color: green;'>Password reset successfully</p>";
        } else {
          $result = "<p style='padding: 20px; border: 1px solid red; color: red;'>The email address provided does not exist in our database. Check your spelling or try another email address, por favor.</p>";
        }
      } catch (PDOException $ex) {
        $result = "<p style='padding: 20px; border: 1px solid red; color: red;'>An error occurred: " . $ex->getMessage() . "</p>";
      }
    }
  } else {
    if(count($form_errors) == 1) {
      $result = "<p style='color: red;'>There was one error in the form</p><br>";
    } else {
      $result = "<p style='color: red;'>There were " . count($form_errors) . " errors in the form</p><br>";
    }
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Password Reset Page</title>
</head>
<body>
  <?php if(isset($result)) echo $result; ?>
  <?php if(!empty($form_errors)) echo show_errors($form_errors); ?>

  <form method="post" action="">
    <table>
      <tr><td>Email:<td><input type="text" value="" name="email"></td></td></tr>
      <tr><td>New Password<td><input type="password" value="" name="new_password"></td></td></tr>
      <tr><td>Confirm Password:</td> <td><input type="password" value="" name="confirm_password"></td></tr>
      <tr><td></td><td><input style="float: right;" type="submit" name="passwordResetBtn" value="Reset Password"></td></tr>
    </table>
  </form>
  <p><a href="index.php">Back</a></p>
</body>
</html>

这是utilities.php中用于检查字段最小长度的函数:

function check_min_length($fields_to_check_length) {
  // initialize an array to store error messages
  $form_errors = array();
  foreach($fields_to_check_length as $name_of_field => $minimum_length_required) {
    if(strlen(trim($_POST[$name_of_field])) < $minimum_length_required) {
      $form_errors[] = $name_of_field . " is too short, must be {$minimum_length_required} characters long";
    }
  }
  return $form_errors;
}

以下是我试图找到$ _POST [&#39; new_password&#39;]值的蹩脚尝试,并将其换成字符串&#34;新密码&#34;

第一次尝试)

if(isset($_POST[$name_of_field]) && $_POST[$name_of_field] == $_POST['new_password']) {
$name_of_field = str_replace($name_of_field, "New password", $_POST['new_password']);
}

第二次尝试)

if(in_array($_POST['new_password'], $form_errors)) {
  $_POST['new_password'] = str_replace($_POST['new_password'], "New Password", $form_errors);
}

我已尝试在主控制器和check_min_length函数中的所有位置进行尝试。我知道我的尝试是可笑的。我一直在尝试学习基本的PHP和编程。

感谢您的时间。

2 个答案:

答案 0 :(得分:0)

我想你应该这样做:

function check_min_length($fields_to_check_length) {
  // initialize an array to store error messages
  $form_errors = array();
  foreach($fields_to_check_length as $name_of_field => $minimum_length_required) {
    if(strlen(trim($_POST[$name_of_field])) < $minimum_length_required) {
      // check name of current field here:
      if ($name_of_field != 'new_password') {
        $form_errors[] = $name_of_field . " is too short, must be {$minimum_length_required} characters long";
      } else {
        $form_errors[] = "New password is too short, must be {$minimum_length_required} characters long";
      }
    }
  }
  return $form_errors;
}

答案 1 :(得分:0)

使用此:

$form_errors = str_replace('new_password', 'New Password', $form_errors);

错误消息只包含输入字段的名称,而不是输入的值。并且您需要将结果分配回数组变量,因为str_replace没有修改数组,它返回一个包含所有替换的新数组。