简体   繁体   中英

How to validate and sanitize array of data in php?

I want to validate and sanitize data which comes from POST array.

My POST data is something like this:

Array
(
    [category_name] => fsdfsfwereq34
    [subCategory] => Array
        (
            [0] => sdfadsffasfasdf
            [1] => sdfasfdsafadsf
            [2] => safdfdasfas
        )

    [category-submitted] => TRUE
)
1

I can validate and sanitize category_name and this is how I do it in PHP.

if (!empty( $_POST['category_name'])) { 
    $category = filter_input(INPUT_POST, 'category_name', FILTER_SANITIZE_STRING);  
} else {
    $category = NULL;
}

But I do not know how to do it for values of the subCategory array. Can anybody tell me how can I do this?

Hope somebody may help me out. Thank you.

You can use foreach to loop through all values of an array. In the loop you can push your filtered values to a new array $subCategory (eg).

Eg:

$subCategory = $_POST['subCategory'];
$subcategories = array();
if (!empty( $subCategory ) && is_array( $subCategory ) ) {
  foreach( $subCategory as $key => $value ) {
    $subCategories[] = filter_var( $value, FILTER_SANITIZE_STRING )
  }
}

You can loop through or for array you use this:

http://php.net/manual/en/function.filter-input-array.php the same way.

After 7 years I propose an answer that complements Siim Kallari's answer and that evaluates POST variables passed by fetch() from javascript in case it can be useful for someone.

You can also use filter_var_array .

$parameters = filter_var_array(json_decode(file_get_contents("php://input"), true), FILTER_SANITIZE_FULL_SPECIAL_CHARS);

I know that this question is 8 years old now (my god), but you can use

$array= map_deep( $array, 'sanitize_text_field' );

to recursively sanitize an entire object/ multi-array and set the original array to it's new value.

See here and here for more information on the two

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM