1

I wrote this to handle sanitizing all the fields in $_POST before saving them to options and to sanitize and initialize everything before creating the form. You can use the same $soap array to handle both input and output.

function sanitize_all ( $dirty, $soap, $args = null ) {
    if ( is_array( $soap ) ) {
        // apply an array of soap to whatever dirt may be available - result keys match soap keys
        $clean = array();
        foreach ( $soap as $key => $suds ) {
            $dirt  = isset( $dirty[$key] ) ? $dirty[$key] : null;
            $_args = isset( $args[$key] ) ? $args[$key] : $args;
            $clean[$key] = sanitize_all( $dirt, $suds, $_args );
        }
    } elseif( is_array( $dirty ) ) {
        // handle an array of dirt with a single bar of soap
        $clean = array();
        foreach ( $dirty as $key => $dirt ) {
            $_args = isset( $args[$key] ) ? $args[$key] : $args;
            $clean[$key] = sanitize_all( $dirt, $soap, $_args );
        }
    } else {
        // set dirty as first parameter and add any others
        if ( is_array( $args ) ) {
            array_unshift( $args, $dirty );
        } elseif ( empty( $args ) ) {
            $args = array( $dirty );
        } else {
            $args = array( $dirty, $args );
        }

        // call the function or filter
        if ( is_callable( $soap ) ) {
            $clean = call_user_func_array( $soap, $args );
        } elseif ( is_string( $soap) ) {
            $clean = apply_filters_ref_array( $soap, $dirty, $args );
        }
    }

    return $clean;
}

USAGE:

$options = sanitize_all( $_POST, array(
  'name' => 'sanitize_text_field',
  'age'  => 'intval',
  'ssn'  => 'sanitize_social'
),
array(
  'ssn'  => array( 'with_dashes' => true )
) );

It think this could be really helpful all over the place maybe even as a function in core. But I wanted to see if anyone had suggestions for improvement before I try to work it into a ticket.

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.