mysql_real_escape_string() 函數轉義 SQL 陳述式中使用的字串中的特殊字元。
下列字元受影響:
如果成功,則該函數返回被轉義的字串。如果失敗,則返回 false。
用法為mysql_real_escape_string(string,connection)
- 參數string,必需。規定要轉義的字串。
- 參數connection,可選。規定 MySQL 串連。如果未規定,則使用上一個串連。
本函數將 string 中的特殊字元轉義,並考慮到串連的當前字元集,因此可以安全用於 mysql_query()。使用本函數來預防資料庫攻擊。
mysql_real_escape_string()的簡單使用
SQL被注入的情況(沒有使用mysql_real_escape_string())
資料庫攻擊。本例示範如果我們不對使用者名稱和密碼應用 mysql_real_escape_string() 函數會發生什麼:
那麼 SQL 查詢會成為這樣:
SELECT * FROM usersWHERE user='john' AND password='' OR ''=''
這意味著任何使用者無需輸入合法的密碼即可登陸。
預防資料庫攻擊的正確做法:
一些經驗
mysql_escape_string()也起到差不多的效果。關於這兩個函數,記得我在用mysql_real_escape_string() 這個函數時,程式總是出錯,不知道錯誤的原因,後來換成mysql_escape_string() 這個函數時,就可以了。尋找手冊,發現在用mysql_real_escape_string() 時,必須要先建立資料庫連接,否則則報錯 -___-|||
mysql_real_escape_string() calls MySQL's library function mysql_escape_string, which prepends backslashes to the following characters: NULL, x00, n, r, , ', " and x1a
mysql_escape_string() does not escape % and _.
This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set. mysql_escape_string() does not take a connection argument and does not respect the current charset setting.
http://www.bkjia.com/PHPjc/752406.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/752406.htmlTechArticlemysql_real_escape_string() 函數轉義 SQL 陳述式中使用的字串中的特殊字元。 下列字元受影響: x00 n r ' x1a 如果成功,則該函數返回被轉義的字元...