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);
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.