Input value and Form submission parameter filtering method to effectively prevent sql injection

  • 2020-12-09 00:47:18
  • OfStack

Input value/form submission parameter filtering to prevent sql injection or illegal attacks:
 
/** 
*  filter sql with php Keywords for file operations  
* @param string $string 
* @return string 
* @author zyb <zyb_icanplay@163.com> 
*/ 
private function filter_keyword( $string ) { 
$keyword = 'select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile'; 
$arr = explode( '|', $keyword ); 
$result = str_ireplace( $arr, '', $string ); 
return $result; 
} 

/** 
*  Check if the number entered is valid and return the corresponding number id Otherwise return false 
* @param integer $id 
* @return mixed 
* @author zyb <zyb_icanplay@163.com> 
*/ 
protected function check_id( $id ) { 
$result = false; 
if ( $id !== '' && !is_null( $id ) ) { 
$var = $this->filter_keyword( $id ); //  filter sql with php Keywords for file operations  
if ( $var !== '' && !is_null( $var ) && is_numeric( $var ) ) { 
$result = intval( $var ); 
} 
} 
return $result; 
} 

/** 
*  Check whether the input character is legal, legal return the corresponding id Otherwise return false 
* @param string $string 
* @return mixed 
* @author zyb <zyb_icanplay@163.com> 
*/ 
protected function check_str( $string ) { 
$result = false; 
$var = $this->filter_keyword( $string ); //  filter sql with php Keywords for file operations  
if ( !empty( $var ) ) { 
if ( !get_magic_quotes_gpc() ) { //  judge magic_quotes_gpc Is it open?  
$var = addslashes( $string ); //  for magic_quotes_gpc Filtering of submitted data when not open  
} 
//$var = str_replace( "_", "\_", $var ); //  the  '_' To filter out  
$var = str_replace( "%", "\%", $var ); //  the  '%' To filter out  
$var = nl2br( $var ); //  Enter conversion  
$var = htmlspecialchars( $var ); // html Tag into  
$result = $var; 
} 
return $result; 
} 

Related articles: