Remove all array elements except what I want?

后端 未结 8 2027
挽巷
挽巷 2021-01-31 14:13

I have controller that takes post parameters from HTML form, it will then send them to model that will insert the array into Cassandra database.

It is SQLInjection proof

8条回答
  •  清歌不尽
    2021-01-31 14:47

    This is called white listing, your example is misleading as the $_POST is an association array.

    $post = [
        'parent_id' => 'val',
        'type' => 'val',
        'title' => 'val',
        'body' => 'val',
        'tags' => 'val',
        'one' => 'val',
        'two' => 'val',
        'three'=>'val',
    ];
    
    $whitelist = ['parent_id', 'type', 'title', 'body', 'tags'];
    
    $sanitized_post = array_whitelist_assoc($post, $whitelist);
    

    This is a whitelisting function I created for associative arrays.

    if(!function_exists('array_whitelist_assoc')){
    
        /**
         * Returns an associative array containing all the entries of array1 which have keys that are present in all the arguments when using their values as keys.
         *
         * @param array $array The array with master keys to check.
         * @param array $array2 An array to compare keys against its values.
         * @return array $array2,... A variable list of arrays to compare.
         * 
         */
    
        function array_whitelist_assoc(Array $array1, Array $array2) {
    
            if(func_num_args() > 2){
                $args = func_get_args();
                array_shift($args);
                $array2 = call_user_func_array('array_merge', $args);
            } 
            return array_intersect_key($array1, array_flip($array2)); 
        }
    }
    

提交回复
热议问题