将mysql真正的转义字符串防止破解?

时间:2011-10-07 21:04:05

标签: php security sql-injection

  

可能重复:
  Are mysql_real_escape_string() and mysql_escape_string() sufficient for app security?

我是PHP的新手并希望确保。如果我使用mysql_real_escape_string作为用户生成的输入(变量),查询将不会被黑客入侵?

示例脚本:

// Getting Unique ID
$sql = "select `Person_id` from `accounts` where `username` = '$username'";
$query = mysql_query($sql) or die ("Error: ".mysql_error());
while ($row = mysql_fetch_array($query)){
    $pid = $row['Person_ID'];
}
mysql_free_result($query);
$username = mysql_real_escape_string($_POST['Username']);
$newname = mysql_real_escape_string($_POST['Full_name']);
$newgender = mysql_real_escape_string($_POST['Patient_gender']);
$newmonth = mysql_real_escape_string($_POST['Month']);
$newday = mysql_real_escape_string($_POST['Day']);
$newyear = mysql_real_escape_string($_POST['Year']);
$newacctss = mysql_real_escape_string($_POST['Acct_SS']);
$newaddress = mysql_real_escape_string($_POST['Address']);
$newaddress2 = mysql_real_escape_string($_POST['Address2']);
$newcity = mysql_real_escape_string($_POST['City']);
$newstate = mysql_real_escape_string($_POST['State']);
$newzipcode = mysql_real_escape_string($_POST['Zip_code']);
$newhomephone = mysql_real_escape_string($_POST['Home_phone']);
$newcellphone = mysql_real_escape_string($_POST['Cell_phone']);
$neworkphone = mysql_real_escape_string($_POST['Work_phone']);
$newsure = mysql_real_escape_string($_POST['Sure']);
$newfav = mysql_real_escape_string($_POST['Favorite']);
$newcars = mysql_real_escape_string($_POST['Cars']);
$newdrinks = mysql_real_escape_string($_POST['Drinks']);
$newmoi = mysql_real_escape_string($_POST['About_moi']);

//Update Name Only
$sql = "UPDATE accounts SET `full_name` = '$newname' WHERE Username = '$username'"; 
$query1 = mysql_query($sql) or die ("Error: ".mysql_error());

//Everything else being udpated here 
$sql2 = "UPDATE profile SET `Patient_gender` = '$newgender', 
`Month` = '$newmonth', `Day` = '$newday', `Year` = '$newyear', 
`Acct_SS` = '$newacctssn', `Address` = '$newaddress', 
`Address2` = '$newaddress2', `City` = '$newcity', `State` = '$newstate', 
`Zip_code` = '$newzipcode', `Home_phone` = '$newhomephone', 
`Cell_phone` = '$cellphone', `Work_phone` = '$neworkphone', 
`Sure` = '$newsure', `Favorite` = '$newfav', `Cars` = '$newcars', 
`Drinks` = '$newdrinks', `About_moi` = '$newmoi' WHERE Person_id = '$pid'"; 
$query2 = mysql_query($sql2) or die ("Error: ".mysql_error());

2 个答案:

答案 0 :(得分:1)

不要直接使用mysql。使用mysqli(注意i)或PDO库并使用预准备语句。使用预准备语句比使用直接查询并在查询字符串中包含变量更安全。

根据PHP文档,mysql will be deprecated。它不再处于不发达状态,而应使用mysqliPDO扩展名。

答案 1 :(得分:0)

如果同时使用引号和mysql_real_escape_string,那么你会非常安全。你可能想看看PDO或至少是mysqli,原因有其他原因。