Sanitize $_POST and $_GET with array_walk

Question

Today I was working with lots of form input which i had to transport through ajax calls. So I wondered if there was a smarter way to handle $_POST (or $_GET) arrays in one go.

I came up with this:

$arr=array('textarea'=>'Line 1
Line 2
<b>bold</b>', 'an_email'=>'bb@bb.com', 'cccc', 'an_url'=>'htTps://domain.tld', 'another_url'=>'http://xxxx?xxx&YYYY','some_html'=>'<b>bold</b>&nbsp;not bold');
print_r($arr);
print_r(clean_array($arr));

function clean_array($input) {
    array_walk (
        $input,
        function (&$value, $key) {
            if ( preg_match('|@|', $value) ) $value=sanitize_email($value);
            else if ( preg_match('|^https?:|i', $value) ) $value=esc_url($value);
            else if ( preg_match('|[nr]|', $value) ) $value=sanitize_textarea_field($value);
            else $value=sanitize_text_field($value);
        }
    );
    return $input;
}

Which will give me:

Array
(
    [textarea] => Line 1
Line 2
<b>bold</b>
    [an_email] => bb@bb.com
    [0] => cccc
    [an_url] => htTps://domain.tld
    [another_url] => http://xxxx?xxx&YYYY
    [some_html] => <b>bold</b>&nbsp;not bold
)
Array
(
    [textarea] => Line 1
Line 2
bold
    [an_email] => bb@bb.com
    [0] => cccc
    [an_url] => https://domain.tld
    [another_url] => http://xxxx?xxx&#038;YYYY
    [some_html] => bold&nbsp;not bold
)

I know that this is probably not the best solution. What do you think?

0
, , , Juergen 8 months 0 Answers 96 views 0

Leave an answer