Check if input file is filled

Asked

Viewed 3,430 times

3

I am having a difficulty that I am not able to solve, even if it is a simple situation. I am trying to validate a field input file, the field needs to be filled in, which I have:

Form:

<form enctype="multipart/form-data" class="form-horizontal" id="frmDoc" method="post">

<legend>Selecione o PDF</legend>
<div class="form-group">
  <label class="col-md-2 control-label">Arquivo</label>
  <div class="col-md-10">
    <input name="Arquivo" type="file" class="btn btn-default" id="Arquivo">
    <p class="help-block"> Extensão permitida <strong>PDF</strong>. </p>
  </div>
</div>

Validation attempt:

if (!isset($_FILES)):
    $retorno = array('codigo' => 0, 'mensagem' => ' Informe o arquivo para Upload');
    echo json_encode($retorno);
    exit();
endif;

The script is running even without informing the file.

2 answers

1


You can do it like this:

if ($_FILES['Arquivo']['error'] == 4):
    $retorno = array('codigo' => 0, 'mensagem' => ' Informe o arquivo para Upload');
    echo json_encode($retorno);
    exit();
endif;

The problem was in the verification, because isset($_FILES) it’s always true, $_FILES always exists, even if it is empty. What I did above was to check whether within that array there is Arquivo defined in the form.

More about upload errors

I also advise you to do a customer side check, with required:

<input name="Arquivo" type="file" class="btn btn-default" id="Arquivo" required>
  • Hello @Miguel, right now informing the file the error message is being displayed, thanks for the tip.

  • How to @adventistapr ? If you upload you get the error message? The file field is called, it has the name "File" right? Not doing well enough?

  • I’m sorry @adventistapr, it was my mistake, I put it correctly now

  • So I made the change as you indicated and the strange is this, even with the field filled my message is displayed, the input field is correct.

  • @adventistapr , no form should not post? ...method='POST'

  • Fixed @adventistapr, sorry, my mistake

Show 1 more comment

1

You can check the file size. If it’s 0 it’s because it wasn’t uploaded.

if ($_FILES['Arquivo']['size'] == 0)

Browser other questions tagged

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