How to Validate Only Jpeg as File Upload Extension?

Asked

Viewed 1,493 times

0

I’m a beginner in programming.

    public function upload(){

    if(Input::hasFile('file')){
        $novonome = uniqid() . '.jpeg';
        $file = Input::file('file');
        $file->move('uploads',$novonome);
        return 'Anexado com sucesso';
    }

    if(UploadedFile::getMaxFilesize()){
        return "Limite máximo de 2 mb";
        }  
    }
  • Which version of Laravel friend?

  • @Leandro Version 5.2

  • have been speaking about this at doc da 5.2 http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html#method_getClientOriginalExtension

  • 1

    @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 ?

  • $extension = File::extension($filename);

  • @Leandro, Putz vei I’m still having doubts to use this File::Xtension in my code !

  • Caleb I answered with some details and examples.

  • 1

    @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 !

  • @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 !

Show 4 more comments

2 answers

2


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)

1

The validation method accepts a request HTTP entry together with its validation rules, if your validation rules pass your code will be executed normally otherwise, will send an error response.

As in the code below:

$validator = Validator::make($request->all(), [
   'image' => 'mimes:jpeg'
];

    if( $validator->fails() ) {
        return $validator->messages();
    }

If the input request parameters do not pass, Laravel will automatically redirect the user to their previous position with all errors updated by session.

To show these errors in view, we can use the code below:

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

This code will basically count the errors, in case these errors exist will show to the end user.

  • Could explain the code?

  • In the Validator variable I am recovering all the fields of the form, said that in the field image can only be accepted images of type jpg, after I made a condition, if there is an error, returns the error message.

  • I think you don’t understand, okay; look, your answer is the best, because I understand a little bit of Laravel and a lot of php and mimetypes, but only code in the answer makes it low quality, the cool is to explain how mimetype works and a little bit of class Validator, well basic, does not need to be anything very detailed, I recommend that follow the example of other answers that have high score, understand as a constructive criticism.

  • 1

    I’m new here at Stack, and I’m sorry I didn’t follow the rules on how to respond properly, so I’m going to dig deeper and see how I respond in quality. Thank you very much for the warning.

  • @Theprince is giving the following error: Unable to Guess the mime type as no guessers are available (Did you enable the php_fileinfo Extension?). I’m a beginner in programming if you can detail for me an answer would be great and very helpful.

  • @Could Guilhermenascimento help me how to perform this comparison to just validate images of type jpeg ? I am beginner

  • The part of php_fileinfo Extension, you have to activate in your php, this link will teach you how to do this https://community.xibo.org.uk/t/how-do-i-enable-fileinfoin-php/78. And a question, you are beginner to php or Laravel?

  • @Caleb that strange by default on PHP5.5 this extension should be enabled.

  • @Theprince, could you edit your answer? As told by William, if you do not improve, your answer runs the risk of being invalidated! Thank you for understanding!

  • I tried to tidy up as best I could, as I said before, I’m new here and I didn’t know how it worked, I apologize for what happened and it won’t happen again.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.