(1) mysql_real_escape_string – Escapes special characters in strings used in SQL statements, taking into account the connection’s current character set
Here’s how to use it:
<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>
Use
<code><span><span>mysql_real_escape_string</span><span>()</span></span></code>
as a wrapper around user input to avoid any malicious SQL injection in user input.
(2) Turn on magic_quotes_gpc to prevent SQL injection
There is a setting in php.ini: magic_quotes_gpc = Off
This is turned off by default. If it is turned on, it will automatically convert the SQL query submitted by the user.
For example, converting ' to ', etc., plays a significant role in preventing SQL injection.
If magic_quotes_gpc=Off, use addslashes() function
(3) Custom function
<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
The above introduces the method (1) of preventing SQL injection in PHP, including all aspects. I hope it will be helpful to friends who are interested in PHP tutorials.