user1829823
user1829823

Reputation: 375

Comparing two passwords PHP

Here's my code it seems to work fine, how ever it doesn't look right. I know I'm vulnerable to injections. Just want to know if the this is the best way of comparing two passwords ?

if (empty($_POST['password'])) {
    $errors[] = "Please enter a password";
} else {
    if ($_POST['password'] != $_POST['password1']) {
        $errors[] = "Your password did not match the confirmed password";
    } else {
        $p = $_POST['password'];
    }
}

Upvotes: 0

Views: 140

Answers (2)

Mubin
Mubin

Reputation: 4455

I suggest You must check both $_POST['password'] and $_POST['password1'] at very beginning.

if (!empty($_POST['password']) && !empty($_POST['password1'])) {
        if (strcmp($_POST['password'], $_POST['password1']) === 0) {
            $p = $_POST['password'];
        } else {
            $errors[] = "Your password did not match the confirmed password";
        }
    } else {
        $errors[] = "Please enter a password";
    }

Upvotes: 0

Naftali
Naftali

Reputation: 146360

Your code is fine, I would just write it a bit differently:

if (empty($_POST['password'])) {
   $errors[] = "Please enter a password";
} elseif($_POST['password'] !== $_POST['password1']) {
   $errors[] = "Your password did not match the confirmed password";
} else {
   $p = $_POST['password'];
}

Upvotes: 5

Related Questions