How to prevent SQL injection by PHP + MySQL

Time:2020-8-1

This article introduces the content of PHP + Mysql to prevent SQL injection method, has a certain reference value, now share with you, friends in need can refer to

 

Method 1

mysql_ real_ escape_ String — escape special characters in strings used in SQL statements, taking into account the current character set of the connection!

$sql = "select count(*) as ctr from users where username

='".mysql_real_escape_string($username)."' and

password='". mysql_real_escape_string($pw)."' limit 1";

 

Method 2

Open magic_ quotes_ GPC to prevent SQL injection. php.ini There is a setting in: magic_ quotes_ GPC = off is off by default. If it is turned on, it will automatically submit the user’s SQL queries for conversion, such as turning ‘to’ and so on, which plays an important role in preventing SQL injection.

If magic_ quotes_ GPC = off, the addslashes() function is used.

Method 3

Custom function

/**

*The first method to prevent SQL injection

* author: xiaochuan

*@ param: mixed $value parameter value

*/ 

function check_param($value=null) { 

        #  select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile

    $str = 'select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile';

  

    if(!$value) {

  

        Exit ('No parameter! ). 

  

    }elseif(eregi($str, $value)) { 

  

        Exit ('illegal parameter! ).

  

    }

  

    return true; 

} 

   

  

  

  

  

  

  

/**

*Method 2 of preventing SQL injection

* author: xiaochuan

*@ param: mixed $value parameter value

*/

function str_check( $value ) { 

  

    if(!get_magic_quotes_gpc()) { 

  

        //Filter 

        $value = addslashes($value); 

  

    } 

  

    $value = str_replace("_", "\_", $value); 

  

    $value = str_replace("%", "\%", $value); 

       

   return $value; 

} 

   

  

  

  

  

  

/**

*The third method to prevent SQL injection

* author: xiaochuan

*@ param: mixed $value parameter value

*/

function post_check($value) { 

  

    if(!get_magic_quotes_gpc()) {

  

        //Filter  

        $value = addslashes($value);

  

    } 

  

    $value = str_replace("_", "\_", $value); 

  

    $value = str_replace("%", "\%", $value); 

  

    $value = nl2br($value); 

  

    $value = htmlspecialchars($value); 

  

    return $value; 

}

 

The above is the details of PHP + Mysql to prevent SQL injection

For more information about PHP, please pay attention to my columnPHP​zhuanlan.zhihu.com