Home  >  Article  >  Backend Development  >  PHP anti-sql injection principle

PHP anti-sql injection principle

(*-*)浩
(*-*)浩Original
2019-10-26 13:18:162469browse

SQL injection: By inserting SQL commands into Web form submissions or entering query strings for domain names or page requests, it ultimately deceives the server into executing malicious SQL commands.

PHP anti-sql injection principle

# Prepared statements are very useful for SQL injection, because different protocols are used after the parameter values ​​are sent, ensuring the legitimacy of the data. Preprocessing is seen as a compiled template of the SQL you want to run, which can be customized using variable parameters. (Recommended learning: PHP video tutorial)

Defense method one

##mysql_real_escape_string – Escape the string used in the SQL statement special characters, taking into account the connection's current character set !

$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. 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 user-submitted queries to sql, such as converting ' to ', etc., to prevent sql Injections make all the difference.

If magic_quotes_gpc=Off, use the addslashes() function.

Method 3:

Custom function

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('没有参数!'); 
    }elseif(eregi($str, $value)) { 
        exit('参数非法!');
    } return true; 

} 
function str_check( $value ) {
   if(!get_magic_quotes_gpc()) { 
   // 进行过滤 
   $value = addslashes($value); 
   } 
   $value = str_replace("_", "\_", $value); 
  $value = str_replace("%", "\%", $value); 
   return $value; 

} 
function post_check($value) { 
        if(!get_magic_quotes_gpc()) {
    
  // 进行过滤  
            $value = addslashes($value);
        } 
        $value = str_replace("_", "\_", $value); 
        $value = str_replace("%", "\%", $value); 
        $value = nl2br($value); 
        $value = htmlspecialchars($value); 
        return $value; 
    }

The above is the detailed content of PHP anti-sql injection principle. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn