我有一个用户注册表格。一切都按预期进行。但是我的团队成员之一从表单中删除了名称和必填属性,并提交了。我的PHP脚本显示注意:未定义的索引:密码。有人可以建议如何解决此问题吗?
处理脚本
function register_user() {
global $connection;
if (is_post_request() && isset($_POST['signup-submit'])) {
$email = escape_string($_POST['email']) ?? NULL;
$username = escape_string($_POST['username']) ?? '';
$password = escape_string($_POST['password']) ?? '';
$country = escape_string($_POST['country']) ?? '';
// * validate inputs
$errors = [];
if (is_blank($email) || !has_valid_email_format($email)) $errors['email'] = 'Looks like this email is incomplete.';
if(!has_uniqueness($email, 's', 'users', 'email')) $errors['email'] = 'Sorry, this email can\'t be registered. Let\'s try another one.';
if (is_blank($username) || !has_format_matching($username, '/^[A-Za-z0-9_]{1,15}$/')) $errors['username'] = 'Username must begin with a letter and can include numbers and underscores.';
if (!has_length($username, ['min' => 6, 'max' => 15])) $errors['username'] = 'Username must be at least 6 characters.';
if(!has_uniqueness($username, 's', 'users', 'username')) $errors['username'] = 'Username is already taken. Please pick a new one.';
if (is_blank($password) || !has_length($password, ['min' => 8])) $errors['password'] = 'Password must be min 8 characters.';
if (is_blank($country)) $errors['country'] = 'Please select your country!';
// * if there were no errors, try to register
if (!empty($errors)) {
return $errors;
} else {
$sql = "INSERT INTO users(username, email, password, country_id, joined) VALUES (?, ?, ?, ?, now())";
$stmt = mysqli_stmt_init($connection);
mysqli_stmt_prepare($stmt, $sql);
// * hashing password
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
mysqli_stmt_bind_param($stmt, 'sssi', $username, $email, $hashed_password, $country);
$result = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
if (!$result) {
exit("Database query failed.");
} else {
$_SESSION['message'] = 'Successfuly Registered!';
redirect_to('index.php');
}
}
}
}
[请让我知道你们是否也想查看该表格:)
使用空合并时,您使用的有点错误
$email = escape_string($_POST['email']) ?? NULL;
它将先执行escape_string($_POST['email'])
,然后再执行空检查。这意味着如果该字段不存在,它将引发错误。
您应该做类似的事情...
$email = escape_string($_POST['email'] ?? "");
使用escape_string($_POST['inputName'] ?? '');
代替escape_string($_POST['inputName']) ?? '';