How to check if the field type="file" was filled

3

I have a form and I 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 through php if the field has been filled

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (empty($_POST["fileToUpload"])) {
        $msg = "Por favor coloque uma imagem!.";
    }
}
    
asked by anonymous 06.10.2016 / 16:04

3 answers

4

Try to do this:

if (!isset($_FILE['fileToUpload'])) {
   $msg = "Por favor coloque uma imagem!.";
}
    
06.10.2016 / 16:33
2

Make sure that the attribute enctype and multipart/form-data are included in the form. 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 it is sent 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!.";
    }
}
    
06.10.2016 / 17:13
2

Basically you should only change% from% to% with%.

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

See the 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 (validar.php):

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