我正在构建一个应用程序,允许用户POST
HTML5 canvas数据,然后在base64中编码并显示给所有用户.我正在考虑将数据解析为实际的.png文件并存储在服务器上,但base64路由允许我将图像存储在数据库中并最小化请求.图像是唯一的,很少,页面不会被刷新.
一些jQuery将获取canvas数据,data:image / png; base64,iVBORw …并将其传递给包含它的PHP脚本,如下所示:< img src =“$data”>< / IMG> 但是,安全性是基石,需要验证base64画布数据,以防止POST请求中传递恶意数据.我的主要关注点是防止将外部URL注入< 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,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;
}
?>