Search code examples
phpfileisset

Checking whether the $_FILES variable is empty when submitted e.g: variableIsEmpty($_FILES["icon"])


I would like to check whether the $_FILES variable is empty when the form is submitted: I have tried this:

if(!isset($_FILES["icon"])){
echo "Empty File";
#code to assign default icon here
}

also this:

if(empty($_FILES["icon"])){
echo "Empty File";
#code to assign default icon here
}

and also this:

if(count($_FILES["icon"]) == 0){
echo "Empty File";
#code to assign default icon here
}

and this is the default else condition for the above, which always executes and means that the above conditions always return false even when I do not select a file:

else {
echo "File is not empty";
}

Is there another way to check if the $_FILES["icon"] variable does not have a value when submitted?

NOTE: enctype="multipart/form-data" has been set in the form and is submitted over POST

Here is the form that submits the icon. The file is a php file and content is added dynamically, this is a section that contains the form:

echo '<form action="' . $_SERVER["PHP_SELF"] . '" method="post" enctype="multipart/form-data">
<input type="file" name="icon"/>Select Icon
<input type="submit" name="upload" value="Upload Icon"/>
</form>';

Then the code that handles the form is also in the same page:

if(isset($_POST["upload"]){
    if(!isset($_FILES["icon"]){
    echo "Empty file":
    #code to assign default icon here
    else {
    $file_gotten = $_FILES["icon];
    }
}

Solution

  • Turns out the variable is actually set because of the input field which is in the form, but attributes of the file such as $_FILES["icon"]["name"], $_FILES["icon"]["tmp_name"] and all those are empty because no file is selected, thanks