PHP 验证 base64 编码的图像

And*_*ner 4 php security xss base64

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

通过验证,我正在考虑 XSS 和其他类似的安全问题。

流程是:

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

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

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

Kar*_*ica 6

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

$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');
}
Run Code Online (Sandbox Code Playgroud)

$mime_type你会得到类似application/pdf或的东西image/jpeg

$file_type你会得到一个文件类型 f.ex。图片。

$extension你之下你会得到一个扩展。

有了finfo_buffer你可以使用一些预定义的常量,它可以给你更多的信息。

使用这些信息,您可以简单地验证它是图像还是 pdf 或您想要检查的任何其他内容。您可以在此页面中查看所有可用的 mimetypes 。


手动的

PHP:finfo_open

PHP:finfo_buffer

PHP:finfo_buffer - 预定义常量

base64_decode

MIME 类型(IANA 媒体类型)