在PHP中检测SVG图像

mmr*_*mrn 2 php svg image

使用PHP,我想检查上传的图像是jpg,gif,png还是svg格式.我发现exif_imagetype函数可以检查文件格式,但它不支持svg格式.有没有办法在PHP中检测svg格式?

krl*_*rle 9

要扩展 Victors 答案,您可以使用mime_content_type('/path/to/file');有关函数,请参阅php.net 手册)并检查返回字符串是否等于image/svg+xml。就像是:

public function isSvg($filePath = '/path/to/file')
{
    return 'image/svg+xml' === mime_content_type($filePath);
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,某些 SVG 文件将被解码为 MIME“image/svg+xml”,而其他文件将只有“image/svg”(没有 XML 部分)。这是由于各种工具的声明和导出造成的。所以我用以下两者检查 SVG: ```$mimeType = mime_content_type($filePath); 返回 preg_match("/SVG/i", $mimeType);``` (2认同)

小智 7

mime_content_type(realpath('img/logo.svg'));
Run Code Online (Sandbox Code Playgroud)

返回"image/svg+xml"。您的 svg 文件必须<xml>在第一行包含标记,如此处所述/sf/answers/3245677361/,类似于<?xml version="1.0" encoding="iso-8859-1"?>


Vic*_*adu 5

永远不要相信文件扩展名来识别文件格式,文件扩展名可能是错误的或更改的.例如,使用mimetype

$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic");
Run Code Online (Sandbox Code Playgroud)

http://www.php.net/manual/en/function.finfo-open.php


小智 -1

pathinfo($_FILES['File']['name'], PATHINFO_EXTENSION)
Run Code Online (Sandbox Code Playgroud)

尽可能使用内置函数,并仅提取所需的信息(选项= PATHINFO_EXTENSION)