Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP -Sanitize values of a array

Tags:

I have a array, which comes from $_POST[] and can have other arrays in it as values, like:

array(  'title' => 'Title',  'data' => array(              'hdr' => 'Header'              'bdy' => 'Body'            ),   'foo' => array(1, 23, 65),   ... ) 

How can I sanitize all values of this big array? for eg. apply a strip_tags() to values like Title, Header, Body, 1, 23, 65 etc ?

like image 216
Alex Avatar asked Feb 01 '11 09:02

Alex


People also ask

What is array values in PHP?

Definition and UsageThe array_values() function returns an array containing all the values of an array. Tip: The returned array will have numeric keys, starting at 0 and increase by 1.

How do you find a specific value in an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

How do you check if a value is in an array PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do I view an array in PHP?

To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array.


2 Answers

Just use the filter extension.

/* prevent XSS. */ $_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING); $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING); 

This will sanitize your $_GET and $_POST.

like image 173
Alfred Avatar answered Oct 29 '22 17:10

Alfred


Have a look at array_map

<?php   $a = array( 'title' => 'Title', 'data' => array(     'hdr' => 'Header',     'bdy' => 'Body'     ), 'foo' => array(1, 23, 65) );  $b = array_map("strip_tags", $a); print_r($b); ?> 

Update for 2D array:

function array_map_r( $func, $arr ) {     $newArr = array();      foreach( $arr as $key => $value )     {         $newArr[ $key ] = ( is_array( $value ) ? array_map_r( $func, $value ) : ( is_array($func) ? call_user_func_array($func, $value) : $func( $value ) ) );     }      return $newArr; } 

Usage:

$a = array( 'title' => 'Title', 'data' => array(     'hdr' => 'Header',     'bdy' => 'Body'     ), 'foo' => array(1, 23, 65) );   $ar =array_map_r('strip_tags', $a); print_r($ar); 

Note I found this just by searching the comments for Dimension

like image 45
kieran Avatar answered Oct 29 '22 16:10

kieran