PHP -Sanitize values of a array

前端 未结 5 905
孤城傲影
孤城傲影 2020-12-01 09:33

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

array(
 \'title\' => \'Title\',
 \'data\' => ar         


        
相关标签:
5条回答
  • 2020-12-01 09:55

    Let's say we want to sanitize the $_POST array:

    foreach($_POST as $k=>$v) {$_POST[$k] = htmlspecialchars($v);}

    This simple. Isn't it?

    0 讨论(0)
  • 2020-12-01 10:01

    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.

    0 讨论(0)
  • 2020-12-01 10:08

    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

    0 讨论(0)
  • 2020-12-01 10:09

    This looks ok, but please comment if it can be improved or has any misgivings:

    $_GET =filter_var_array($_GET);
    $_POST=filter_var_array($_POST);
    
    0 讨论(0)
  • 2020-12-01 10:19
    function strip($string, $allowed_tags = NULL)
    {
        if (is_array($string))
        {
            foreach ($string as $k => $v)
            {
                $string[$k] = strip($v, $allowed_tags);
            }
            return $string;
        }
    
        return strip_tags($string, $allowed_tags);
    }
    

    Just an example of a recursive function, for stripping tags in this case.

    $arr = strip($arr);
    
    0 讨论(0)
提交回复
热议问题