PHP mysql_real_escape_string() 函數
轉自:http://www.w3school.com.cn/php/func_mysql_real_escape_string.asp
定義和用法
mysql_real_escape_string() 函數轉義 SQL 語句中使用的字符串中的特殊字符。
下列字符受影響:
- /x00
- /n
- /r
- /
- '
- "
- /x1a
如果成功,則該函數返回被轉義的字符串。如果失敗,則返回 false。
語法
mysql_real_escape_string(string,connection)
參數 | 描述 |
---|---|
string | 必需。規定要轉義的字符串。 |
connection | 可選。規定 MySQL 連接。如果未規定,則使用上一個連接。 |
說明
本函數將 string 中的特殊字符轉義,並考慮到連接的當前字符集,因此可以安全用於 mysql_query()。
提示和註釋
提示:可使用本函數來預防數據庫攻擊。
例子
例子 1
<?php $con = mysql_connect("localhost", "hello", "321"); if (!$con) { die('Could not connect: ' . mysql_error()); } // 獲得用戶名和密碼的代碼 // 轉義用戶名和密碼,以便在 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
數據庫攻擊。本例演示如果我們不對用戶名和密碼應用 mysql_real_escape_string() 函數會發生什麼:
<?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);
// 不檢查用戶名和密碼
// 可以是用戶輸入的任何內容,比如:
$_POST['user'] = 'john';
$_POST['pwd'] = "' OR ''='";
// 一些代碼...
mysql_close($con);
?>
那麼 SQL 查詢會成爲這樣:
SELECT * FROM users WHERE user='john' AND password='' OR ''=''
這意味着任何用戶無需輸入合法的密碼即可登陸。
例子 3
預防數據庫攻擊的正確做法:
<?php function check_input($value) { // 去除斜槓 if (get_magic_quotes_gpc()) { $value =stripslashes($value)
; } // 如果不是數字則加引號 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); ?>