7

Using PHP, I'd like to check if a uploaded image is in jpg, gif, png, or svg format. I found exif_imagetype function could check the file format, but it does not support svg format. Is there any way to detect svg format in PHP?

mmrn
  • 249
  • 2
  • 8
  • 18

5 Answers5

12

To extend Victors answer, you can use mime_content_type('/path/to/file'); (see php.net manual for the function) and check if the return string is equal to image/svg+xml. Something like:

public function isSvg($filePath = '/path/to/file')
{
    return 'image/svg+xml' === mime_content_type($filePath);
}
krle
  • 123
  • 1
  • 7
  • 2
    Beware that certain SVG files will be decoded as MIME `image/svg+xml` whilst others will have just `image/svg` (w/o XML part). This is due to declaration and export by various tools out there. So I check SVG with both: ```$mimeType = mime_content_type($filePath); return preg_match("/SVG/i", $mimeType);``` – stamster Mar 23 '21 at 00:27
7
mime_content_type(realpath('img/logo.svg'));

return "image/svg+xml". Your svg file must contain <xml> tag at first line as described here https://stackoverflow.com/a/46366819, something like <?xml version="1.0" encoding="iso-8859-1"?>

1
mime_content_type($filePath);

Be careful if svg file is startting from <svg xmlns="http://www.w3.org/2000/svg" width="210" height="80"> i'm getting "text/html"

ruslan
  • 23
  • 6
-1
pathinfo($_FILES['File']['name'], PATHINFO_EXTENSION)

Use a built-in function whenever possible, and Extract only the needed information (options = PATHINFO_EXTENSION)

Gogul
  • 298
  • 2
  • 14
  • 1
    keep in mind, that that check is not to be trusted. E.g. if the user did upload that file the user could easily change a file extension in many cases. – Hafenkranich Jan 29 '20 at 22:04
-1

Try this one-

$extensions= array("jpeg","jpg","png","svg","gif");    
$file_ext       = strtolower(end(explode('.',$file['name'])));
if(in_array($file_ext,$extensions)=== true){
    ...
    ...
}