How do I sanitize meta box contents to prevent XSS attacks?

276 Views Asked by At

I know how to sanitize metabox content like

<img src=x onerror=console.log(hey) /> 

But how about the following?

<img src=x onerror=console.log(hey)<img src="x" />

Tried the code below, but doesn't seem to work.

wp_kses_post()

Tried using balanceTags(), striplashes(), wp_kses_post(), etc.

sanitize_text_field() would work obviously but it'd filter out all the HTML.

1

There are 1 best solutions below

1
Moishy On

if storing to the database you should use sanitze functions. if your outputting to the browser you should use escape functions.

<img src=<?php echo esc_url('x'); ?> onerror=<?php echo esc_attr('console.log(hey)'); ?><img src="<?php echo esc_url('x'); ?>" />

using wp_kses

$string = '<img src=x onerror=console.log(hey)<img src="x" />';

<?php echo wp_kses( $string, array( 'img' => array('src' => array() ), 'p' => array() ) ); ?>

or

<?php echo wp_kses( $string, 'data' ); ?>