How to implement a php framework series [5] securely process input,
Check validity of all external input parameters.
Improper processing of input data may result in SQL injection and other vulnerabilities.
The framework provides a series of functions to get the value in $ _ REQUEST.
RequestInt
RequestString
RequestFloat
RequestBool
Ps:Note that the variable type in $ _ REQUEST may be an array.
If the request is? I [] = 1, then the value of $ _ REQUEST ['I'] Is array (1)
Comprehensive considerations should be taken into consideration during verification to prevent php warning Information Leakage
In addition, we will introduce the data validation in kv json format.
Sometimes data in json format is used to retain certain scalability in the project. How can this data be verified.
// Verify json data in the key value format {k1: v1, k2: v2, k3: v3...}. Each kv pair can be verified.
RequestKvJson
Partial implementation code
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
// Check the integer. $ default is returned if an error occurs. function checkInt( $var , $default = 0) { return is_numeric ( $var ) ? intval ( $var , ( strncasecmp ( $var , '0x' , 2) == 0 || strncasecmp ( $var , '-0x' , 3) == 0) ? 16 : 10) : $default ; } // Check string $ check as a regular expression function checkString( $var , $check = '' , $default = '' ) { if (! is_string ( $var )) { if ( is_numeric ( $var )) { $var = (string) $var ; } else { return $default ; } } if ( $check ) { return (preg_match( $check , $var , $ret ) ? $ret [1] : $default ); } return $var ; } /* Verify kv json, If you want such data {id: 1, 'type': 'Single _ text', 'required': true, 'desc': 'This is a text '} Then $ desc can be written in this way. array( array('id', 'Int'), array('type', 'string', PATTERN_NORMAL_STRING), array('required', 'Bool', false), array('desc', 'string', PATTERN_NORMAL_STRING), )) */ function checkKvJson( $var , $desc = array ()) { if ( is_string ( $var )) { $var = json_decode( $var , true); } if (! $var || ! is_array ( $var )) { return array (); } if ( $desc ) foreach ( $desc as $d ) { if (!isset( $var [ $d [0]])) { return array (); } $ps = array_slice ( $d , 2); array_unshift ( $ps , $var [ $d [0]]); $var [ $d [0]] = call_user_func_array( 'check' . $d [1], $ps ); if ( $var [ $d [0]] === false && strcasecmp ( $d [1], 'Bool' )) { return array (); } } return $var ; } |