How to check if type="file" field has been filled

Asked

Viewed 1,181 times

3

I have a form and have the following field

<div class="form-group">
        <label for="foto">Foto:</label>
        <input type="file" name="fileToUpload" id="fileToUpload" accept="image/*" required>
</label>

I need to check in php if the field has been filled

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (empty($_POST["fileToUpload"])) {
        $msg = "Por favor coloque uma imagem!.";
    }
}
  • 1

    Unused $_POST for an input file, use $_FILES

  • 1

    if (isset($_FILES['fileToUpload'])) {} else {}

3 answers

4


Try to do so:

if (!isset($_FILE['fileToUpload'])) {
   $msg = "Por favor coloque uma imagem!.";
}
  • So you are only creating a String variable if you do not have a file. You have to show the message somewhere. if (!isset($_FILE['fileToUpload'])) { $msg = "Please insert an image!." ; echo $msg; }

  • Unnecessary your comment!

4

Check if the attribute is included in the form: enctype and with the value multipart/form-data. This value is required when you are using forms that have a file upload control.

The enctype attribute specifies how the data form should be encoded when sending it to the server. It can be used only if the method is "post".

Form suggestion:

<form method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="foto">Foto:</label>
        <input type="file" name="fileToUpload" id="fileToUpload" accept="image/*" required> 
        <input type="submit" value="Salvar" name="submit">  
    </div>
</form>

Validation:

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (empty($_FILES["fileToUpload"])) {
        $msg = "Por favor coloque uma imagem!.";
    }
}
  • If you make a var_dump($_FILES["fileToUpload"]); will be displayed some data from the file that was uploaded.

2

Basically you should just change $_POST for $_FILES.

I took the required of your html for validation to work, so using the data you passed would look like this:

View code in operation.

HTML:

<form id="formulario" name="formulario" method="post" action="validar.php">
    <div class="form-group">
        <label for="foto">Foto:</label>
        input type="file" name="fileToUpload" id="fileToUpload" accept="image/*">
        </label><br><br>
    <input id="btnenviar" name="btnenviar" type="submit" value="Validar" />
</form>

PHP (validate.php):

<?php
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        if (empty($_FILES["fileToUpload"])) {
            $msg = "Por favor coloque uma imagem!.";
            echo $msg;
        }
    }
?>

Browser other questions tagged

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