0

I have a problem validating a file upload.

To be sure a user uploads a valid image (not a file with extension .jpg or .png,...) one can use getimagesize(). For example: W3school .

But what about an .svg file? The function getimagesize() returns nothing when I use print_r(). How could I be sure that user uploads a .svg file, not a file with extension .svg (virus.svg)?

bart
  • 14,958
  • 21
  • 75
  • 105

1 Answers1

-1

If you're OK with using external scripts, you can use the SVG Sanitize package: https://packagist.org/packages/enshrined/svg-sanitize

While its primary purpose is sanitation, as a by-product of that process, it will also ensure your SVG is valid.

use enshrined\svgSanitize\Sanitizer;

// Create a new sanitizer instance
$sanitizer = new Sanitizer();

// Load the dirty svg (if it's an SVG file)
$dirtySVG = file_get_contents('filthy.svg');

// if it's a base64 encoded string, you can alternatively use the following
$base64_str = str_replace('data:image/svg+xml;base64,', '', $b64_string);
$base64_str = str_replace(' ', '+', $base64_str);
$dirtySVG = base64_decode($base64_str);

// Pass it to the sanitizer and get it back clean
if(!$cleanSVG = $sanitizer->sanitize($dirtySVG)){
    //if this fails, the SVG was not valid.
}

// Now do what you want with your validated and clean SVG/XML data
dearsina
  • 4,774
  • 2
  • 28
  • 34