(1)mysql_real_escape_string – 轉義 SQL 語句中使用的字串中的特殊字元,並考慮到連接的當前字元集
使用方法如下:
<code>$sql = "<span><span>select</span><span>count</span>(*) <span>as</span> ctr <span>from</span> users <span>where</span> username =<span>'".mysql_real_escape_string($username)."'</span><span>and</span> password=<span>'". mysql_real_escape_string($pw)."'</span> limit <span>1</span><span>";</span></span></code>
使用
<code><span><span>mysql_real_escape_string</span><span>()</span></span></code>
作為使用者輸入的包裝器,就可以避免使用者輸入中的任何惡意 SQL 注入。
(2) 開啟magic_quotes_gpc來防止SQL注入
php.ini中有一個設定:magic_quotes_gpc = Off
這個預設是關閉的,如果它打開後將自動把用戶提交對sql的查詢進行轉換,
例如把 ’ 轉為 ’等,對於防止sql注射有重大作用。
如果magic_quotes_gpc=Off,則使用addslashes()函數
(3)自訂函數
<code><span><span>function</span><span>inject_check</span><span>(<span>$sql_str</span>)</span> {</span><span>return</span> eregi(<span>'select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile'</span>, <span>$sql_str</span>); } <span><span>function</span><span>verify_id</span><span>(<span>$id</span>=null)</span> {</span><span>if</span>(!<span>$id</span>) { <span>exit</span>(<span>'没有提交参数!'</span>); } <span>elseif</span>(inject_check(<span>$id</span>)) { <span>exit</span>(<span>'提交的参数非法!'</span>); } <span>elseif</span>(!is_numeric(<span>$id</span>)) { <span>exit</span>(<span>'提交的参数非法!'</span>); } <span>$id</span> = intval(<span>$id</span>); <span>return</span><span>$id</span>; } <span><span>function</span><span>str_check</span><span>( <span>$str</span> )</span> {</span><span>if</span>(!get_magic_quotes_gpc()) { <span>$str</span> = addslashes(<span>$str</span>); <span>// 进行过滤 </span> } <span>$str</span> = str_replace(<span>"_"</span>, <span>"\_"</span>, <span>$str</span>); <span>$str</span> = str_replace(<span>"%"</span>, <span>"\%"</span>, <span>$str</span>); <span>return</span><span>$str</span>; } <span><span>function</span><span>post_check</span><span>(<span>$post</span>)</span> {</span><span>if</span>(!get_magic_quotes_gpc()) { <span>$post</span> = addslashes(<span>$post</span>); } <span>$post</span> = str_replace(<span>"_"</span>, <span>"\_"</span>, <span>$post</span>); <span>$post</span> = str_replace(<span>"%"</span>, <span>"\%"</span>, <span>$post</span>); <span>$post</span> = nl2br(<span>$post</span>); <span>$post</span> = htmlspecialchars(<span>$post</span>); <span>return</span><span>$post</span>; }</code>
http://www.phpddt.com/php/228.html
以上就介紹了PHP防止SQL注入的方法(1),包括了面向的內容,希望對PHP教學有興趣的朋友有幫助。