我正在构建一个允许用户使用 POST
的应用程序然后以 base64 编码并显示给所有用户的 HTML5 Canvas 数据。我正在考虑将数据解析为实际的 .png 文件并存储在服务器上,但是 base64 路由允许我将图像存储在数据库中并最大限度地减少请求。图片独特,数量少,页面不会经常刷新。
一些 jQuery 将获取 Canvas 数据,data:image/png;base64,iVBORw...
并将其传递给像这样包装它的 PHP 脚本:<img src="$data"></img>
然而,安全是基石,需要验证 base64 Canvas 数据以防止在 POST
中传递恶意数据。要求。我主要关心的是防止外部 URL 被注入(inject)到 <img>
中。标记并在页面加载时被请求。
我目前有这样的设置:
$data = (isset($_POST['canvas']) && is_string($_POST['canvas'])) ? $_POST['canvas'] : null;
$base = str_replace('data:image/png;base64,', '', $data);
$regx = '~^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$~'
if ((substr($data, 0, 22)) !== 'data:image/png;base64,')
{
// Obviously fake, doesn't contain the expected first 22 characters.
return false;
}
if ((base64_encode(base64_decode($base64, true))) !== $base64)
{
// Decoding and re-encoding the data fails, something is wrong
return false;
}
if ((preg_match($regx, $base64)) !== 1)
{
// The data doesn't match the regular expression, discard
return false;
}
return true;
我想确保我当前的设置足够安全,以防止外部 URL 被插入到 <img>
中标签,如果没有,可以做些什么来进一步验证图像数据?
最佳答案
执行此操作的一种方法是从 base64 数据实际创建图像文件,然后使用 PHP 验证图像本身。可能有更简单的方法来执行此操作,但这种方法肯定有效。
请记住,这仅适用于 PNG,如果您计划允许更多文件类型(GIF、JPG),则需要添加一些逻辑。
<?
$base64 = "[insert base64 code here]";
if (check_base64_image($base64)) {
print 'Image!';
} else {
print 'Not an image!';
}
function check_base64_image($base64) {
$img = imagecreatefromstring(base64_decode($base64));
if (!$img) {
return false;
}
imagepng($img, 'tmp.png');
$info = getimagesize('tmp.png');
unlink('tmp.png');
if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
return true;
}
return false;
}
?>
关于php - 验证 base64 编码的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12658661/