jh95 jh95 - 9 months ago 44
PHP Question

How do I redirect a user to the same URL if the password/email validation fails?

I have a password reset script that has email and password validation. How can I make the script redirect the user to the same URL (ie. "https://www.domain.com/resetpassword.php?token=...") if they fail to meet the validation? Currently, if the validation test fails, the user is redirected to the URL: https://www.domain.com/resetpassword.php. The token is now gone and the password reset page becomes useless.

Here is my PHP code:

include 'connect.php';

// Was the form submitted?
if (isset($_POST['btn-reset']))
// Gather the post data
$email = trim($_POST['email']);
$email = strip_tags($email);

$pass = trim($_POST['pass']);
$pass = strip_tags($pass);

$cpass = trim($_POST['cpass']);
$cpass = strip_tags($cpass);

//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";


// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have at least 6 characters.";
} else if($pass != $cpass) {
$error = true;
$passError = "Passwords do not match.";
// if there's no error, continue to process
if( !$error ) {

$token = $_POST ['token'];

// Retrieve token from database
$stmt = $conn->prepare('SELECT token FROM token WHERE userEmail=? and NOW() < expire_date');
$stmt->bind_param('s', $email);

$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
$resetKey = $row['token'];
// Does the new reset key match the old one?
if ($resetKey == $token && isset($token))
if ($pass == $cpass)
//hash and secure the password
$password = password_hash($pass, PASSWORD_DEFAULT);

// Update the user's password
$stmt = $conn->prepare('UPDATE user SET userPass = ? WHERE userEmail = ?');
$stmt->bind_param('ss', $password, $email);
$conn = null;
$sucMSG = "Your password has been successfully reset.";
$matchError = "Your password's do not match.";
$keyError = "Your password reset key is invalid.";

And then I have the errors appear in my form using PHP if the values of the errors are set.

Answer Source

Try this: Put this in a functions.php file.

  function redirect_to($new_location) {
    header("Location: " . $new_location);

Now use this: