可能重复:
如何防止 PHP 中的 SQL 注入?
我想问一些关于防止 sql 注入的问题。从我一直在阅读的内容中,我不断遇到以下三件事:
- 带斜杠
- 与magic_quotes_gpc一起使用
- mysql_real_escape_string (或我想在较新的 php 中的 mysqli?)
问题是,我应该同时使用这两种方法还是 real_escape_string 就足够了?
例如,我有这行与注册页面有关的代码(我知道事实上它很容易受到攻击,因为 sqli 助手让我可以找到关于我的数据库的所有内容:(因为我还没有实现上述任何内容):
if(isset($_POST['submit'])){
//cleanup the variables
$username = ($_POST['username']);
$password = ($_POST['password']);
$email = ($_POST['email']);
$username = sanitise($username);
$password = sanitise($password);
$email = sanitise($email);
//quick/simple validation
if(empty($username)){ $action['result'] = 'error'; array_push($text,'Please type in a username'); }
if(empty($password)){ $action['result'] = 'error'; array_push($text,'Please type in a password'); }
if($action['result'] != 'error'){
$password = md5($password);
//add to the database
$add = mysql_query("INSERT INTO Users VALUES(NULL,'$username','$password','$email',0, 'First', 'Last', 'Phone Number Here', '...', 'Something about me...')");
if($add){
//get the new user id
$userid = mysql_insert_id();
//create a random key
$key = $username . $email . date('mY');
$key = md5($key);
//add confirm row
$confirm = mysql_query("INSERT INTO Confirm VALUES(NULL,'$userid','$key','$email')");
if($confirm){
//include the swift class
include_once 'swift/swift_required.php';
//put info into an array to send to the function
$info = array(
'username' => $username,
'email' => $email,
'key' => $key);
//send the email
if(send_email($info)){
//email sent
$action['result'] = 'success';
array_push($text,'Thanks for signing up. Please check your e-mail for confirmation.');
}else{
$action['result'] = 'error';
array_push($text,'Could not send confirmation e-mail');
}
}else{
$action['result'] = 'error';
array_push($text,'Confirm row was not added to the database. Reason: ' . mysql_error());
}
}else{
$action['result'] = 'error';
array_push($text,'User could not be added to the database. Reason: ' . mysql_error());
}
}
$action['text'] = $text;
}
?>
我认为我的消毒功能会有所帮助 - 把它放到网上,但它看起来有点没用。或者它可能只有助于防止跨站点脚本。这里是:
function cleanInput($input) {
$search = array(
'@<script[^>]*?>
.*?</script>@si', // Strip out javascript
'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
'@<style[^>]*?>.*?
</style>
@siU', // Strip style tags properly
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments
);
$output = preg_replace($search, '', $input);
return $output;
}
function sanitise($input) {
if (is_array($input)) {
foreach($input as $var=>$val) {
$output[$var] = sanitise($val);
}
}
else {
if (get_magic_quotes_gpc()) {
$input = stripslashes($input);
}
$input = cleanInput($input);
$output = $input;
}
return $output;
}
你会建议这个功能没用吗?
如果是这样,我将如何保护原始代码?即:
$username = ($_POST['username']);
$password = ($_POST['password']);
$email = ($_POST['email']);