The validation by file extension is not safe, this link does not contain the answer to "Laravel" (although it may work) but it explains the problem that validations by extension can cause:
The preferable is to validate via mimetype, for this use so:
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';
}
the getMimeType()
takes the file mimetype instead of the extension, because as I said here the extension may not be from a valid file.
You can also use the class Request
+ Validation
, and a detail, that method you used UploadedFile::getMaxFilesize()
not to validate, just to know the limit that is possible to upload varying with PHP settings, use the Validator
to limit the file weight.
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 so:
extension=php_fileinfo.dll
After this restart Apache or Ngnix (or whatever your server is)
Which version of Laravel friend?
– Leandro
@Leandro Version 5.2
– Caleb
have been speaking about this at doc da 5.2 http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html#method_getClientOriginalExtension
– Leandro
@Leandro, I got to look, but I did not understand how to use correctly, would have to demonstrate the use of Symfony based on the above problem ?
– Caleb
$extension = File::extension($filename);
– Leandro
@Leandro, Putz vei I’m still having doubts to use this File::Xtension in my code !
– Caleb
Caleb I answered with some details and examples.
– Guilherme Nascimento
@Guilhermenascimento Putz guy Thank you so much for the strength ! I am beginner in programming, so sometimes I keep bumping heads on small things ! With his explanation gave to understand the functioning of the perfect mime ! Thanks a lot !
– Caleb
@Guilhermenascimento Take away a doubt, how would I check the fileinfo extension via php ? Because I would need to run this code on another machine then it would give me the feedback if the extension is active or not. Then I would use another code without using mime type in a very weak way, to make the comparison of extension. If you could help, I’d be very grateful !
– Caleb