0

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];
    }
}
Cypherjac
  • 859
  • 8
  • 17
  • https://www.php.net/manual/en/features.file-upload.post-method.php Might want to check for `$_FILES["icon"]["name"]` or any/some of the other attributes – brombeer Apr 26 '20 at 10:41
  • could you add your form that sends this request? – Joseph Apr 26 '20 at 10:49
  • Does this answer your question? [Why would $\_FILES be empty when uploading files to PHP?](https://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php) – Salim Ibrohimi Apr 26 '20 at 10:50
  • to @kerbholz: I have tried this: ```if(isset($_FILES["icon"]["name"])){ echo "Image has a name, and the name is" . $_FILES["icon"]["name"]; ``` and this is the output: ```Image has a name, and the name is ``` , this means that it is empty, but it is there even though I did not select any file – Cypherjac Apr 26 '20 at 11:21
  • The array key is set, but it is empty, try with the `empty` function, or with an implicit bool cast: `if (empty(...))` or `if (...)` – Emanuel Vintilă Apr 26 '20 at 11:27
  • Thanks @Emanuel, I've tried this: ```if(empty($_FILES["icon"]["name"])){ echo "File is empty": }```, and it works fine, thanks a lot. – Cypherjac Apr 26 '20 at 11:32

1 Answers1

0

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

Cypherjac
  • 859
  • 8
  • 17