File extension validation is not secure, this link does not contain the answer to "Laravel" (although it may work) but explains the problem that extensions can cause:
It is preferable to validate via mimeType, so use this:
if(Input::hasFile('file')){
$file = Input::file('file');
if($file->getMimeType() === 'image/jpeg') {
$novonome = uniqid() . '.jpeg';
$file->move('uploads',$novonome);
return 'Anexado com sucesso';
}
return 'Só é permitido imagens JPEG';
}
getMimeType()
takes the mimeType of the file instead of the extension, because as I said here the extension may not be a valid file.
You can also use the class Request
+ Validation
, and a detail, this method that used UploadedFile::getMaxFilesize()
is not valid, just to know the limit that can be uploaded varying with PHP settings , use Validator
to limit the weight of the file.
public function upload(Request $req)
{
//Verifica se o campo veio vazio
if (!$file->hasFile('file')) {
return 'Não foi enviado a foto';
}
//Pega o arquivo
$file = $request->file('file');
$input = [
'file' => $file
];
/*
* Regras da validação, como mimetype e tamanho máximo
* 2048 é igual a 2mb, altere conforme a necessidade
*/
$rules = [
'file' => 'image|mimes:jpeg|max:2048'
];
$messages = [
'mimes' => 'Formato invalido'
];
$validator = Validator::make($input, $rules, $messages);
if ($validator->fails()) {
return $validator->messages();
}
$novonome = uniqid() . '.jpeg';
$file->move('uploads', $novonome);
return 'Anexado com sucesso';
}
Enabling fileinfo
To enable fileinfo you need to edit php.ini and uncomment this line:
;extension=php_fileinfo.dll
Leaving thus:
extension=php_fileinfo.dll
After this restart Apache or Ngnix (or whatever your server)