如何防止更新表单上的密码字段双重md5?

时间:2011-03-30 21:24:29

标签: php passwords md5

在我的用户信息更新表单中,我让用户更新传递以及其他内容。如果他们不想更新表单中的密码,则将其留空,因为该字段为空。在进程页面上,如果该字段为空,我从db(其md5)插入现有密码,如果他们更改了它,我想要新密码。下面是我用来尝试实现的,但它是双md5-ing无论如何:

      if (!get_magic_quotes_gpc()) {

$newpass = mysql_escape_string($_POST['password']);
$newpass = md5($_POST['password']);

    }

    // If $dob is empty
    if (empty($newpass)) {

    $newpass = "$passis"; //$passis = the password stored in db which is md5
        }

3 个答案:

答案 0 :(得分:2)

$newpass永远不会为空,因为md5会将空字符串转换为哈希值。因此,这种情况不起作用:if (empty($newpass)) {

相反,你必须做

 if (empty($_POST['password'])) {

<强>更新

 if (!get_magic_quotes_gpc()) {

$newpass = mysql_escape_string($_POST['password']);
$newpass = md5($_POST['password']);

}

// If $dob is empty
if (empty($_POST['password'])) { 
   $newpass = "$passis"; //$passis = the password stored in db which is md5
}

答案 1 :(得分:1)

只需对代码进行一些修改:

  $newpass = $_POST['password'];

  if (!get_magic_quotes_gpc()) {
      $newpass = mysql_escape_string($newpass);
  }

  if(empty($newpass)) {
    $newpass = "$passis"; //$passis = existing md5'd password already stored in db
  }
  else {
    $newpass = md5($newpass); //$newpass = newly provided password needs to be md5'd before updating db
  }     

答案 2 :(得分:1)

您的代码很奇怪,因为只有设置了magic_quotes_gpc指令才会执行md5。
另一个想法是空字符串的md5不是空字符串。

这是一个应该更好用的代码:

$newpass = isset($_POST['password']) ? $_POST['password'] : '';
if ($newpass=='') {
  $newpass = $passis; // $passis = the password stored in db which is md5
} else {
  if (get_magic_quotes_gpc()) $newpass = stripslashes($newpass); // take off slashes added by PHP if any
  $newpass = md5($newpass);
}