PHP验证base64编码的图像



我需要找到一种方法来验证用PHP编码的base64图像。

通过验证,我想到了XSS和其他类似的安全功能。

流程为:

用户有一些参数,其中一个或多个在base64编码字符串的图像,并将它们发布到我的网站。当我接收到名为img1的参数fx时,该参数的值为base64编码的图像字符串。

然后我想确保这个base64编码的字符串只由图像组成,没有任何标签和黑客试图使用的任何其他东西。

有人知道任何PHP函数或插件可以帮助我吗?

您可以使用以下代码验证文件类型:

$file = 'Your base64 file string';
$file_data = base64_decode($file);
$f = finfo_open();
$mime_type = finfo_buffer($f, $file_data, FILEINFO_MIME_TYPE);
$file_type = explode('/', $mime_type)[0];
$extension = explode('/', $mime_type)[1];
echo $mime_type; // will output mimetype, f.ex. image/jpeg
echo $file_type; // will output file type, f.ex. image
echo $extension; // will output extension, f.ex. jpeg
$acceptable_mimetypes = [
    'application/pdf',
    'image/jpeg',
];
// you can write any validator below, you can check a full mime type or just an extension or file type
if (!in_array($mime_type, $acceptable_mimetypes)) {
    throw new Exception('File mime type not acceptable');
}
// or example of checking just a type
if ($file_type !== 'image') {
    throw new Exception('File is not an image');
}

$mime_type下,您将获得类似application/pdfimage/jpeg的内容。

$file_type下,您将获得一个文件类型f.ex.image。

根据$extension,您将获得延期。

使用finfo_buffer,您可以使用一些预定义的常量,这可能会给您提供更多信息。

有了这些信息,你可以简单地验证它是图像还是pdf或任何其他你想检查的东西。您可以在此页面中查看所有可用的mimetype。


手动

PHP:finfo_open

PHP:finfo_buffer

PHP:finfo_buffer-预定义常量

base64_代码

MIME类型(IANA媒体类型)

您可以尝试使用imagecreatefromstring函数从字符串中创建图像。

然后可以测试图像尺寸/类型。

如果你想更进一步,你可以创建一个新的图像,然后尝试将用户图像复制到它上,并将其用作最终图像。由于最终的图像最初是由你创建的,任何黑客都很难通过。

我只会把base64编码的字符串放在图像标签中。但在我正在构建的系统中,安全性是非常重要的,所以我只需要确保像XSS这样的东西不能用于base64编码的图像:)

然后,您可以像处理任何其他用户输入一样执行此操作:在将用户提供的文本放入HTML之前,先对其进行htmlspecialchars编码,以保持HTML的完整性。Base64图像字符串也不例外。参见伟大的逃避主义(或者:在文本中使用文本需要知道什么)。

当然,一团图像数据可能会通过易受攻击的图像解析器向您打开完全不同的攻击向量。因此,您可能需要先将该图像字符串解码为图像资源,然后使用gd或Imagick函数再次保存,即打开并重新保存/重新编码图像。

试试这个库

https://github.com/imaimai86/Intervention-Base64Image

它使用干预图像库来验证base64编码图像

$str = 'your  base64 code' ;
if (base64_encode(base64_decode($str, true)) === $str && imagecreatefromstring(base64_decode($img))) {
echo 'Success! The String entered match base64_decode and is Image';
}

最新更新