'image' 规则是否足够安全?
Is 'image' rule secure enough?
所以我正在尝试为我的网站创建上传个人资料图片...而且我想知道 image
规则在 Laravel 中是否足够安全。
考虑以下代码:
input = [
'profile_picture' => Input::file('profile_picture'),
];
$rules = ['profile_picture' => 'required|image'];
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return 'It\'s not an image!';
}
很简单,我希望您关注的是 rules
数组中的 image
规则。
似乎 Laravel 通过 MIME 类型验证图像。正如我们所知,它可以从客户端进行编辑,然后使用 Tamper Data 或 Burp Proxy 之类的东西发送到服务器。
你说你怎么知道它通过 MIME 类型验证图像?嗯...看看下面这段代码,这是 Laravel 用于验证的 Validator.php
class。它包含了我认为的所有规则。具体来说,这是 validateImage
函数,也就是 image
规则。
Validator/validateImage():
/**
* Validate the MIME type of a file is an image MIME type.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
protected function validateImage($attribute, $value)
{
return $this->validateMimes($attribute, $value, array('jpeg', 'png', 'gif', 'bmp'));
}
正如 Doc-block 所说,它通过其 MIME 类型对其进行验证。
那么它是否足够安全?欢迎提问!
回答你的问题我们不能说任何安全与否。
但是 Laravel 仅验证您指定的几种格式的图像。也提到here。
如果你认为这是一个基本的验证,那么你应该使用像this这样的第三方包,它按宽高比验证图像(只有真实图像才有)
不,它不安全。至少你不能确定它是否是真实图像,因为 MIME 类型可以被操纵。通常有用的是使用 getimagesize()
如果文件不是图像,它将 return false
。所以你可以用这个规则扩展验证器:
Validator::extend('real_image', function($attribute, $value, $parameters){
if($value instanceof Symfony\Component\HttpFoundation\File\UploadedFile){
if(getimagesize($value->getRealPath() !== false){
return true;
}
}
return false;
}
并将其添加到您的验证规则中:
$rules = ['profile_picture' => 'required|image|real_image'];
所以我正在尝试为我的网站创建上传个人资料图片...而且我想知道 image
规则在 Laravel 中是否足够安全。
考虑以下代码:
input = [
'profile_picture' => Input::file('profile_picture'),
];
$rules = ['profile_picture' => 'required|image'];
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return 'It\'s not an image!';
}
很简单,我希望您关注的是 rules
数组中的 image
规则。
似乎 Laravel 通过 MIME 类型验证图像。正如我们所知,它可以从客户端进行编辑,然后使用 Tamper Data 或 Burp Proxy 之类的东西发送到服务器。
你说你怎么知道它通过 MIME 类型验证图像?嗯...看看下面这段代码,这是 Laravel 用于验证的 Validator.php
class。它包含了我认为的所有规则。具体来说,这是 validateImage
函数,也就是 image
规则。
Validator/validateImage():
/**
* Validate the MIME type of a file is an image MIME type.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
protected function validateImage($attribute, $value)
{
return $this->validateMimes($attribute, $value, array('jpeg', 'png', 'gif', 'bmp'));
}
正如 Doc-block 所说,它通过其 MIME 类型对其进行验证。
那么它是否足够安全?欢迎提问!
回答你的问题我们不能说任何安全与否。
但是 Laravel 仅验证您指定的几种格式的图像。也提到here。
如果你认为这是一个基本的验证,那么你应该使用像this这样的第三方包,它按宽高比验证图像(只有真实图像才有)
不,它不安全。至少你不能确定它是否是真实图像,因为 MIME 类型可以被操纵。通常有用的是使用 getimagesize()
如果文件不是图像,它将 return false
。所以你可以用这个规则扩展验证器:
Validator::extend('real_image', function($attribute, $value, $parameters){
if($value instanceof Symfony\Component\HttpFoundation\File\UploadedFile){
if(getimagesize($value->getRealPath() !== false){
return true;
}
}
return false;
}
并将其添加到您的验证规则中:
$rules = ['profile_picture' => 'required|image|real_image'];