我编写了一个运行良好的 PHP 注册/登录系统。但是,我尝试添加一些服务器端错误检查,以防止用户在不输入密码的情况下进行注册,检查密码字段是否匹配等。这是我的代码:
<?php
session_start();
// retrieve data via POST
$username = $_POST['username'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$userLoc = $_POST['userLoc']; // user location is a field on the submitted form
include("config.php");
$username = mysqli_real_escape_string($conn, $username); // clean username input
// ensure that the two password fields match
if ($pass1 != $pass2) {
header('Location: ../');
die();
}
// ensure that the user didn't bypass maxlength for username
if(strlen($username) > 30) {
header('Location: ../');
die();
}
// ensure that the user actually entered a password
if( strlen($pass1<3) || strlen($pass2<3) ) {
header('Location: ../');
die();
}
// check if username already taken
// I'm using a session variable that causes a div to be displayed on index.php to indicate username taken
// (I also have AJAX username check already implemented)
$query = "SELECT 1 FROM users WHERE username='$username'";
$result = mysqli_query($conn,$query);
if ( $result && mysqli_num_rows($result) > 0 ) {
$_SESSION['usernameTaken'] = 1;
header('Location: ../');
}
// create hash for password
$hash = hash('sha256', $pass1);
// create salt for password
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
$userLoc = mysqli_real_escape_string($conn, $userLoc);
$query = "INSERT INTO users ( username, password, salt, userLoc ) VALUES ( '$username' , '$hash' , '$salt' , '$userLoc' );";
mysqli_query($conn,$query);
mysqli_close();
header('Location: ../');
?>
这是我无法弄清楚的问题:使用那里的die();
语句,如果满足任何条件(密码不匹配,用户名已经存在等),脚本实际上会自行终止,它被正确重定向到 index.php( ../
),并且用户名没有添加到数据库中。然而,即使没有触发任何错误检查逻辑(换句话说,用户名可用,密码匹配等),用户名也不会被添加到数据库中。我能够将任何内容添加到数据库的唯一方法是删除每个die()
语句,但这使得错误检查不起作用(例如,我可以输入不匹配的密码,并且用户名仍然会与散列一起添加到数据库中pass1
)。
我认为这是因为die()
即使给定的if
语句没有评估为真,语句也会被触发。有什么建议么?