PHP mysql_real_escape_string() 函數(shù)
定義和用法
mysql_real_escape_string() 函數(shù)轉(zhuǎn)義 SQL 語句中使用的字符串中的特殊字符。
下列字符受影響:
- \x00
- \n
- \r
- \
- '
- "
- \x1a
如果成功,則該函數(shù)返回被轉(zhuǎn)義的字符串。如果失敗,則返回 false。
語法
mysql_real_escape_string(string,connection)
參數(shù) | 描述 |
---|---|
string | 必需。規(guī)定要轉(zhuǎn)義的字符串。 |
connection | 可選。規(guī)定 MySQL 連接。如果未規(guī)定,則使用上一個連接。 |
說明
本函數(shù)將 string 中的特殊字符轉(zhuǎn)義,并考慮到連接的當(dāng)前字符集,因此可以安全用于 mysql_query()。
提示和注釋
提示:可使用本函數(shù)來預(yù)防數(shù)據(jù)庫攻擊。
例子
例子 1
<?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); ?>
例子 2
數(shù)據(jù)庫攻擊。本例演示如果我們不對用戶名和密碼應(yīng)用 mysql_real_escape_string() 函數(shù)會發(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 查詢會成為這樣:
SELECT * FROM users WHERE user='john' AND password='' OR ''=''
這意味著任何用戶無需輸入合法的密碼即可登陸。
例子 3
預(yù)防數(shù)據(jù)庫攻擊的正確做法:
<?php function check_input($value) { // 去除斜杠 if (get_magic_quotes_gpc()) { $value =stripslashes($value)
; } // 如果不是數(shù)字則加引號 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()); } // 進行安全的 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); ?>