【发布时间】:2018-01-05 20:21:15
【问题描述】:
我试图创建一个限制,当您输入数据库中已经存在的用户名或电子邮件时,显示一条消息说已经存在。但是当我尝试时,它只是忽略了代码。
<?php
include 'config.php';
$sql_en = mysqli_query($conn, "SELECT `password`, `method` FROM `encryption`");
if (mysqli_num_rows($sql_en) > 0) {
while($row = mysqli_fetch_assoc($sql_en)) {
$password = $row["password"];
$method = $row["method"];
}
} else {
echo "Error to find the keys to encrypt!";
}
if (isset($_POST["u_btn"])) {
$u_name = $_POST["u_name"];
$u_email = $_POST["u_email"];
$u_pass = $_POST["u_pass"];
if (empty($u_name) || empty($u_email) || empty($u_pass) ) {
echo "Fill out all the fields!";
} else {
$check = mysqli_query($conn, "SELECT * FROM users where u_email = '$u_email' AND u_name = '$u_name'");
$row = mysqli_fetch_array($check);
if ($row["u_email"] == $u_email || $row["u_name"] == $u_name) {
echo "Username already exists!";
header('Location: register.php?err=true');
} else {
$encrypt_pass = $u_pass;
// Must be exact 32 chars (256 bit)
$password = substr(hash('sha256', $password, true), 0, 32);
// IV must be exact 16 chars (128 bit)
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
$encrypted = base64_encode(openssl_encrypt($encrypt_pass, $method, $password, OPENSSL_RAW_DATA, $iv));
$insert = mysqli_query($conn,"INSERT INTO `users` (`u_name`, `u_email`, `u_pass`) VALUES ('$u_name', '$u_email', '$encrypted')");
header('Location: profile.php');
}
}
}
?>
<?php if (isset($_GET['err1'])) { ?>
<div class="alert">
<p>Login Failed! That username or email already exists! Do you wanto to go to the login page? <a href="login.php">Login</a>.</p>
</div><?php } ?>
<?php if (isset($_GET['err2'])) { ?>
<div class="alert">
<p>Login Failed! That username or email already exists! Do you wanto to go to the login page? <a href="login.php">Login</a>.</p>
</div><?php } ?>
<form action="register.php" method="post">
<label>Name</label>
<input type="text" name="u_name" value="" ></input><br />
<label>Email</label>
<input type="email" name="u_email" value="" ></input><br />
<label>Password</label>
<input type="password" name="u_pass" value="" ></input><br />
<input type="submit" name="u_btn" value="Sing Up"></input>
<input type="button" onclick="window.location='login.php';" value="Login"></input>
</form>
问题在于,如果我将电子邮件和姓名放入数据库中,代码可以工作,但如果我只输入姓名或电子邮件,则不会检查它是否已经存在。
【问题讨论】:
-
请使用 PHP 的built-in functions 来处理密码安全问题。如果您使用低于 5.5 的 PHP 版本,您可以使用
password_hash()compatibility pack。 在散列之前不需要escape passwords 或对它们使用任何其他清理机制。这样做会更改密码并导致不必要的额外编码。