0

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('|[\n\r]|', $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?

  • 2
    This looks more like a generic PHP question, you'd get more answers on stackoverflow for this type of question. Keep in mind that you need to know the type of data to sanitise and validate it properly, and you can't use the value to do that. I could pass a URL into a checkbox field, an email into a URL field, etc and your code would sanitize them despite them being incorrect. There are also other basic PHP APIs for interacting with GET and POST that aren't $_GET or $_POST, e.g. filter_input – Tom J Nowell Jun 9 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.