Mat*_*t M 1 php mysql xss mysqli sql-injection
我正在尝试创建一个安全的注册表单,这只是前几个字段将会有大约十几个字段,但这是无关紧要的.我有点安全性很好,我想知道以下代码是否足以防止XSS和SQL注入.
我已经包含了表单的开头,只是为了表明我需要发布自己的自我.
if(isset($_POST['submit'])){
$firstname = htmlentities($_POST['firstname'], ENT_QUOTES, 'UTF-8');
$lastname = htmlentities($_POST['lastname'], ENT_QUOTES, 'UTF-8');
$email = htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8');
$emailrepeat = htmlentities($_POST['emailrepeat'], ENT_QUOTES, 'UTF-8');
$password = htmlentities($_POST['password'], ENT_QUOTES, 'UTF-8');
$passwordrepeat = htmlentities($_POST['passwordrepeat'], ENT_QUOTES, 'UTF-8');
if (empty($firstname))
{
$fnError = "Please Enter Your First Name";
}
if (empty($lastname))
{
$lnError = "Please Enter Your Last Name";
}
$getEmail = $mysqli->prepare('SELECT * FROM users WHERE email=?');
$getEmail->bind_param('s', $email);
$getEmail->execute();
$getEmail->store_result();
$countRows = $getEmail->num_rows;
if ($countRows > 0)
{
$emError = "Email Address Already Exists";
$countRows = 0;
}
else if (empty($email))
{
$emError = "Please Enter an Email Address";
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emError = "Invalid Email Address";
}
else if ($email != $emailrepeat)
{
$emError = "Emails do not match";
}
if (empty($password))
{
$pwError = "Please Enter a Password";
}
else if (strlen($password)<6)
{
$pwError = "Password must be atleast 6 characters";
}
else if ($password != $passwordrepeat)
{
$pwError = "Emails do not match";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
if ($password == $passwordrepeat and !empty($password) and strlen($password)>5)
{
$pwhash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));
if($stmt = $mysqli->prepare("INSERT INTO users (first_name, last_name, email, password) VALUES (?, ?, ?, ?)"))
{
$stmt->bind_param("ssss", $firstname, $lastname, $email, $pwhash);
$stmt->execute();
$stmt->close();
}
}
}
}
<form id="addnewuser" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
</form>
Run Code Online (Sandbox Code Playgroud)1.赞美使用准备好的陈述!
2.阅读以下内容
总的来说,从安全角度来看,这看起来相当不错,但你肯定会在htmlentities()任何地方使用它来解决问题.
根据您的逻辑,如果我想使用密码,ThisIsSo<Secu>r那么您的代码将转换为它,ThisIsSo<Secu>r因此除非您也使用htmlentities()登录页面的用户名/密码,否则我无法登录您的网站.
将用户数据保存到数据库时,应始终保持用户键入内容的完整性,并在回显数据时实现正确的转义.这个例外就像CKEditor; 但编辑负责为你逃跑.
为了更好地说明这一点,您将希望使用htmlentities()如下:
<div class="welcome-banner">Welcome <?php echo htmlentities($row['firstname']); ?>!</div>
Run Code Online (Sandbox Code Playgroud)
或者像这样:
<h3>Editing Your Profile</h3>
<label>First Name</label><br>
<input type="text" name="firstname" value="<?php echo htmlentities($row['firstname']); ?>">
Run Code Online (Sandbox Code Playgroud)