← Back to All Snippets

Sanitize Uploaded SVG Files to Prevent Stored XSS Attacks

⚡ Target: functions.php 🔒 Tested: WP 6.6+ / PHP 8.2+ 💻 Lang: PHP
PHP (functions.php)
// 1. Allow SVG Mime Type
add_filter( 'upload_mimes', function( $mimes ) {
    $mimes['svg'] = 'image/svg+xml';
    $mimes['svgz'] = 'image/svg+xml';
    return $mimes;
} );

// 2. Sanitize SVG XML Content on Upload
add_filter( 'wp_handle_upload_prefilter', function( $file ) {
    if ( 'image/svg+xml' === $file['type'] || 'image/svg' === $file['type'] ) {
        $svg_content = file_get_contents( $file['tmp_name'] );
        // Remove dangerous script, iframe, and object tags
        $clean_svg = preg_replace( '/<(script|iframe|object|embed)[^>]*?>.*?<\/(script|iframe|object|embed)>/si', '', $svg_content );
        $clean_svg = preg_replace( '/on\w+="[^"]*"/i', '', $clean_svg );
        $clean_svg = preg_replace( '/javascript:/i', '', $clean_svg );
        file_put_contents( $file['tmp_name'], $clean_svg );
    }
    return $file;
} );

Enables SVG file uploads while stripping malicious embedded JavaScript tags, onclick handlers, and foreign entities before saving to disk.

← Back to All Snippets Explore Dev Tools →