PHP mysql_real_escape_string() 函數(shù)
定義和用法
mysql_real_escape_string() 函數(shù)轉(zhuǎn)義 SQL 語(yǔ)句中使用的字符串中的特殊字符。
下列字符受影響:
如果成功,則該函數(shù)返回被轉(zhuǎn)義的字符串。如果失敗,則返回 false。
mysql_real_escape_string(string,connection)
參數(shù) 描述
string 必需。規(guī)定要轉(zhuǎn)義的字符串。
connection 可選。規(guī)定 MySQL 連接。如果未規(guī)定,則使用上一個(gè)連接。
本函數(shù)將 string 中的特殊字符轉(zhuǎn)義,并考慮到連接的當(dāng)前字符集,因此可以安全用于 mysql_query()。
提示和注釋
提示:可使用本函數(shù)來(lái)預(yù)防數(shù)據(jù)庫(kù)攻擊。
<?php
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
? {
? die('Could not connect: ' . mysql_error());
? }
// 獲得用戶名和密碼的代碼
// 轉(zhuǎn)義用戶名和密碼,以便在 SQL 中使用
$user = mysql_real_escape_string($user);
$pwd = mysql_real_escape_string($pwd);
$sql = "SELECT * FROM users WHERE
user='" . $user . "' AND password='" . $pwd . "'"
// 更多代碼
mysql_close($con);
?>
數(shù)據(jù)庫(kù)攻擊。本例演示如果我們不對(duì)用戶名和密碼應(yīng)用 mysql_real_escape_string() 函數(shù)會(huì)發(fā)生什么:
<?php
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
? {
? die('Could not connect: ' . mysql_error());
? }
$sql = "SELECT * FROM users
WHERE user='{$_POST['user']}'
AND password='{$_POST['pwd']}'";
mysql_query($sql);
// 不檢查用戶名和密碼
// 可以是用戶輸入的任何內(nèi)容,比如:
$_POST['user'] = 'john';
$_POST['pwd'] = "' OR ''='";
// 一些代碼...
mysql_close($con);
?>
那么 SQL 查詢會(huì)成為這樣:
SELECT * FROM users
WHERE user='john' AND password='' OR ''=''
這意味著任何用戶無(wú)需輸入合法的密碼即可登陸。
預(yù)防數(shù)據(jù)庫(kù)攻擊的正確做法:
<?php
function check_input($value)
{
// 去除斜杠
if (get_magic_quotes_gpc())
? {
? $value = stripslashes($value);
? }
// 如果不是數(shù)字則加引號(hào)
if (!is_numeric($value))
? {
? $value = "'" . mysql_real_escape_string($value) . "'";
? }
return $value;
}
$con = mysql_connect("localhost", "hello", "321");
if (!$con)
? {
? die('Could not connect: ' . mysql_error());
? }
// 進(jìn)行安全的 SQL
$user = check_input($_POST['user']);
$pwd = check_input($_POST['pwd']);
$sql = "SELECT * FROM users WHERE
user=$user AND password=$pwd";
mysql_query($sql);
mysql_close($con);
?>