PHP mysql_real_escape_string的一處注意_PHP教程

來源:互聯網
上載者:User
mysql_real_escape_string() 函數轉義 SQL 陳述式中使用的字串中的特殊字元。

下列字元受影響:

  • x00
  • n
  • r
  • '
  • "
  • x1a

如果成功,則該函數返回被轉義的字串。如果失敗,則返回 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 如果成功,則該函數返回被轉義的字元...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.