php mysql_real_escape_string函數(shù)用法與實(shí)例教程
下列字符受影響:
- \x00
- \n
- \r
- \
- '
- "
- \x1a
如果成功,則該函數(shù)返回被轉(zhuǎn)義的字符串。如果失敗,則返回 false。
語(yǔ)法
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ù)來預(yù)防數(shù)據(jù)庫(kù)攻擊。
例子
例子 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ù)庫(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 ''=''這意味著任何用戶無需輸入合法的密碼即可登陸。
例子 3
預(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);
?>
- PHP中的MYSQL常用函數(shù)(php下操作數(shù)據(jù)庫(kù)必備)
- 解析php session_set_save_handler 函數(shù)的用法(mysql)
- PHP函數(shù)addslashes和mysql_real_escape_string的區(qū)別
- php Mysql日期和時(shí)間函數(shù)集合
- php empty函數(shù)判斷mysql表單是否為空
- PHP訪問MYSQL數(shù)據(jù)庫(kù)封裝類(附函數(shù)說明)
- PHP持久連接mysql_pconnect()函數(shù)使用介紹
- PHP操作mysql函數(shù)詳解,mysql和php交互函數(shù)
- php中使用session_set_save_handler()函數(shù)把session保存到MySQL數(shù)據(jù)庫(kù)實(shí)例
- Zend studio for eclipse中使php可以調(diào)用mysql相關(guān)函數(shù)的設(shè)置方法
- PHP mysqli_free_result()與mysqli_fetch_array()函數(shù)詳解
- PHP_MySQL教程-第三天 基本函數(shù)
- PHP操作MySQL的mysql_fetch_* 函數(shù)的常見用法教程
- php mysql_list_dbs()函數(shù)用法示例
- PHP mysql_real_escape_string()
相關(guān)文章
不用數(shù)據(jù)庫(kù)的多用戶文件自由上傳投票系統(tǒng)(1)
不用數(shù)據(jù)庫(kù)的多用戶文件自由上傳投票系統(tǒng)(1)...2006-10-10用Apache反向代理設(shè)置對(duì)外的WWW和文件服務(wù)器
用Apache反向代理設(shè)置對(duì)外的WWW和文件服務(wù)器...2006-10-10