Media PHP Advanced

Allow Safe SVG Uploads for Admins

Let administrators upload SVG files, with each file rebuilt from an allowlist so scripts, event handlers and external links never get through.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 74 lines
// Allow SVG uploads for administrators only.
add_filter( 'upload_mimes', function ( array $mimes ): array {
	if ( current_user_can( 'manage_options' ) ) {
		$mimes['svg'] = 'image/svg+xml';
	}
	return $mimes;
} );

// Some servers can't detect the SVG type from the file contents.
add_filter( 'wp_check_filetype_and_ext', function ( array $data, string $file, string $filename ): array {
	if ( current_user_can( 'manage_options' ) && 'svg' === strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ) ) {
		$data['ext']  = 'svg';
		$data['type'] = 'image/svg+xml';
	}
	return $data;
}, 10, 3 );

// Rebuild every SVG from an allowlist before WordPress saves it.
add_filter( 'wp_handle_upload_prefilter', function ( array $file ): array {
	if ( 'svg' !== strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) ) ) {
		return $file;
	}
	$clean = nahnu_sanitize_svg( (string) file_get_contents( $file['tmp_name'] ) );
	if ( null === $clean ) {
		$file['error'] = 'This SVG could not be read safely, so it was not uploaded.';
		return $file;
	}
	file_put_contents( $file['tmp_name'], $clean );
	return $file;
} );

function nahnu_sanitize_svg( string $svg ): ?string {
	$tags  = [ 'svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'text', 'tspan', 'defs',
		'lineargradient', 'radialgradient', 'stop', 'clippath', 'mask', 'pattern', 'title', 'desc', 'use', 'symbol' ];
	$attrs = [ 'viewbox', 'width', 'height', 'x', 'y', 'x1', 'x2', 'y1', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'd', 'points',
		'fill', 'fill-rule', 'fill-opacity', 'clip-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
		'stroke-miterlimit', 'stroke-dasharray', 'stroke-opacity', 'opacity', 'transform', 'id', 'class', 'offset',
		'stop-color', 'stop-opacity', 'gradientunits', 'gradienttransform', 'patternunits', 'clip-path', 'mask',
		'font-size', 'font-family', 'font-weight', 'text-anchor', 'version', 'preserveaspectratio', 'href', 'xlink:href' ];

	if ( '' === trim( $svg ) || false !== stripos( $svg, '<!ENTITY' ) ) {
		return null;
	}

	$dom  = new DOMDocument();
	$prev = libxml_use_internal_errors( true );
	$ok   = $dom->loadXML( $svg, LIBXML_NONET );
	libxml_clear_errors();
	libxml_use_internal_errors( $prev );
	if ( ! $ok || ! $dom->documentElement || 'svg' !== strtolower( $dom->documentElement->localName ) ) {
		return null;
	}

	$clean = function ( DOMElement $el ) use ( &$clean, $tags, $attrs ): void {
		foreach ( iterator_to_array( $el->attributes ) as $attr ) {
			$name  = strtolower( $attr->nodeName );
			$value = trim( $attr->value );
			$link  = in_array( $name, [ 'href', 'xlink:href' ], true );
			if ( ! in_array( $name, $attrs, true ) || ( $link && ! str_starts_with( $value, '#' ) ) || preg_match( '/javascript:|data:|url\s*\(\s*[\'"]?\s*(?!#)/i', $value ) ) {
				$el->removeAttributeNode( $attr );
			}
		}
		foreach ( iterator_to_array( $el->childNodes ) as $child ) {
			if ( $child instanceof DOMElement && in_array( strtolower( $child->localName ), $tags, true ) ) {
				$clean( $child );
			} elseif ( ! ( $child instanceof DOMText ) || $child instanceof DOMCdataSection ) {
				$el->removeChild( $child );
			}
		}
	};
	$clean( $dom->documentElement );

	return $dom->saveXML( $dom->documentElement );
}

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

SVG files are XML documents, and XML can carry scripts, event handlers like onload, links to other sites and external entities. That’s why WordPress blocks SVG uploads by default. This snippet allows them for administrators and rebuilds every uploaded file so only drawing instructions survive.

How it works

Only users with manage_options can upload SVGs, through the upload_mimes and wp_check_filetype_and_ext filters. Every SVG then passes through nahnu_sanitize_svg() before WordPress saves it.

The sanitizer loads the file with PHP’s DOM parser, with network access off, and rejects anything that declares entities. It then walks every element and keeps it only if its tag is on an allowlist of shapes, text, gradients and grouping elements. Every attribute must also be on an allowlist. Links may only point inside the same file (#id), and values containing javascript:, data: or external url() references are removed. Comments, processing instructions, CDATA and <style> and <script> elements are all dropped.

The old version stripped <script> tags and on* attributes with regular expressions. That’s easy to get around, for example with an unquoted event handler or a javascript: link, and left sites open to stored cross-site scripting. An allowlist only keeps what it knows is safe.

Things to watch

  • Inline style attributes and <style> blocks are removed. Export SVGs with presentation attributes (most design tools have this option), or add styling in your theme’s CSS.
  • Animated or interactive SVGs lose their scripts and animation elements.
  • WordPress can’t create thumbnails for SVGs, so they may appear blank in some media grid views.

How to test it

Upload a normal logo SVG and insert it in a post. Then upload a test file containing <svg onload="alert(1)">: it uploads, but opening the saved file shows the onload attribute is gone.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only