PHP methods for preventing SQL injection (1)

Source: Internet
Author: User
(1) mysql_real_escape_string– escaped in the string used in the SQL statement Special Characters, taking into account the current character set of the connection
Here's how to use it:

$sql = "selectcount(*) as ctr from users where username ='".mysql_real_escape_string($username)."'and password='". mysql_real_escape_string($pw)."' limit 1";

Use

mysql_real_escape_string()

As a wrapper for user input, you can avoid any malicious SQL injection in user input.
(2) Open MAGIC_QUOTES_GPC to prevent SQL injection
There is a setting in php.ini: MAGIC_QUOTES_GPC = Off
This is off by default, and if it is turned on, it will automatically convert the query that the user commits to SQL.
For example, "switch to \" And so on, to prevent SQL injection has a major role.
If Magic_quotes_gpc=off, use the addslashes () function
(3) Custom functions

 functioninject_check($sql _str) {returnEregi (' select|insert|and|or|update|delete|\ ' |\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile ',$sql _str);} functionverify_id($id=null) {if(!$id) {Exit(' No submission Parameters! '); }ElseIf(Inject_check ($id)) {Exit(' The arguments submitted are illegal! '); }ElseIf(!is_numeric ($id)) {Exit(' The arguments submitted are illegal! '); }$id= Intval ($id);return$id; } functionstr_check( $str ) {if(!GET_MAGIC_QUOTES_GPC ()) {$str= Addslashes ($str);//Filter}$str= Str_replace ("_","\_",$str);$str= Str_replace ("%","\%",$str);return$str; } functionpost_check($post) {if(!GET_MAGIC_QUOTES_GPC ()) {$post= Addslashes ($post); }$post= Str_replace ("_","\_",$post);$post= Str_replace ("%","\%",$post);$post= NL2BR ($post);$post= Htmlspecialchars ($post);return$post; }

Http://www.phpddt.com/php/228.html

The above describes the PHP method to prevent SQL injection (1), including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.