我的问题是如何让注册页面更安全?在register.html上,用户添加了一些数据,如果在register.php中,用户名存在于数据库中,则告诉他使用另一个用户名。
对SQL注入是否很差?另一方面,我如何确保用户只使用字母数字字符?
register.php
$sql ="SELECT * FROM $table_name WHERE username= '$_POST[username]'";
$result = @mysql_query($sql,$connection) or die(mysql_error());
//get the number of rows in the result set
$num = mysql_num_rows($result);
//checks it see if that username already exists
if ($num != 0){
echo "<P>Sorry, that username already exists.</P>";
echo "<P><a href=\"#\" onClick=\"history.go(-1)\">Try Another Username.</a></p>";
exit;
}else{
$sql = "INSERT INTO $table_name VALUES
('$_POST[firstname]', '$_POST[lastname]', '$_POST[username]', password('$_POST[password]'), 'Users', '', '', '$pchange',
'$_POST[email]', '$default_url', '$verify', '')";
答案 0 :(得分:1)
永远不会将值从用户直接传递到数据库
查看mysql_real_escape_string()
http://php.net/manual/en/function.mysql-real-escape-string.php
答案 1 :(得分:0)
使用prepared statements而不是将参数嵌入到sql查询
中 $pdo = new PDO(*pdo parameters here*);
$sql = "SELECT * FROM $table_name WHERE username= ?";
$stmt = $pdo->prepare($sql);
$rslt = $stmt->execute(array($_POST[username]));
if (!$rslt){
var_dump($stmt->errorInfo());
}
$num = $stmt->rowCount();
// ................//
else{
$sql = "INSERT INTO $table_name VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
$stmt_ins = $pdo->prepare($sql);
$stmt_ins->execute(array(
$_POST[firstname],
$_POST[lastname],
$_POST[username],
password($_POST[password]),
'Users', '', '', $pchange,
$_POST[email], $default_url, $verify, ''
));
}
答案 2 :(得分:0)
您应该使用mysql_real_escape_string()来清理所有POST值,从而避免SQL注入攻击。
尝试使用此功能:
<?php
//This stops SQL Injection in POST vars
foreach ($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);
}
//This stops SQL Injection in GET vars
foreach ($_GET as $key => $value) {
$_GET[$key] = mysql_real_escape_string($value);
}
?>
被盗:http://www.php.net/manual/en/function.mysql-real-escape-string.php#92649