【问题标题】:(PHP) How can I validate the .svg (file upload)(PHP)如何验证 .svg(文件上传)
【发布时间】:2018-07-28 18:19:33
【问题描述】:

我在验证文件上传时遇到问题。

为了确保用户上传有效的图像(不是扩展名为 .jpg 或 .png 的文件,...),可以使用 getimagesize()。例如:W3school

但是 .svg 文件呢?当我使用print_r() 时,函数getimagesize() 什么也不返回。我如何确定用户上传的是 .svg 文件,而不是扩展名为 .svg (virus.svg) 的文件?

【问题讨论】:

标签: php svg getimagesize


【解决方案1】:

如果您可以使用外部脚本,可以使用 SVG Sanitize 包:https://packagist.org/packages/enshrined/svg-sanitize

虽然其主要目的是卫生,但作为该过程的副产品,它还将确保您的 SVG 有效。

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

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 2013-03-13
    • 2017-03-26
    • 2015-10-31
    • 2018-07-19
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    相关资源
    最近更新 更多