tags:

views:

45

answers:

1

I had an inefficient piece of code for resetting passwords based on a user entering either their username or their email address. The PHP script branched depending on the identifier used. I collapsed it into one which now works if the user enters their username but not if they enter their email address. Here is the salient code:

$identifier = isset($_POST["username"])?"username":"email";
$ident = isset($_POST["username"])?trim(mysqli_real_escape_string($mysqli,(check_chars_username($_POST["username"])))):trim(mysqli_real_escape_string($mysqli, (check_chars_email($_POST["email"]))));


    //create and issue the query
    $sql = "SELECT * FROM aromaMaster WHERE $identifier = '$ident'";
    $sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));

    if(mysqli_num_rows($sql_res) == 0) {
      //wrong login info
      header("Location: password_reset_form.html/error=$ident");
      exit();
    }
      $info = mysqli_fetch_array($sql_res);
        $userid = $info["id"];
        $username = stripslashes($info["username"]);
        $email = stripslashes($info["email"]);

I have checked and doubled checked that the email form field is called email and it is. It's got me scratching my head. Particularly interesting is the header redirect. When I enter an email address and am redirected, the variable $ident appears empty.

A: 

As you've noted in your comment, you have to check for the username variable of the $_POST array to be empty.

It's also a good idea to check if the variable is even there in the first place in addition to and before you test against it being blank.

$identifier = 
 (isset($_POST["username"]) && !empty($_POST["username"])) ? "username":"email";

When you're sending your form across, all of the text input fields will come through, even if they're blank. Blank is not the same as empty. That's the reason the first part of the ternary operator is always true in your initial code.

random