16

Here is the form

form action="index.php" method="POST" enctype="multipart/form-data" >
        <input type="file" name="image[]" multiple="multiple">
        <input type="submit" value="upload">
    </form> 

I am trying to only run my code when only when if(!empty($_FILES['image'])){ but for some reason the array is not empty upon submitting no files and only clicking submit.

Here is the rest of the code if that will help, thanks.

<html>

Image Upload

    <form action="index.php" method="POST" enctype="multipart/form-data" >
        <input type="file" name="image[]" multiple="multiple">
        <input type="submit" value="upload">
    </form> 

    <?php

    include 'connect.php';

    if(!empty($_FILES['image'])){
    echo $_FILES['image']['error'];
        $allowed = array('jpg', 'gif', 'png', 'jpeg');
        $count = 0;

        foreach($_FILES['image']['name'] as $key => $name){
        $image_name = $name;
        $tmp = explode('.', $image_name);
        $image_extn = strtolower(end($tmp)); //can only reference file
        $image_temp = $_FILES['image']['tmp_name'][$count];
        $filesize = filesize($_FILES['image']['tmp_name'][$count]);
        $count = $count +1;

        if(count($_FILES['image']['tmp_name']) > 5){
            echo "You can upload a maximum of five files.";
            break;
        }

        else if(in_array($image_extn, $allowed) === false){
            echo $name." is not an allowed file type<p></p>";
        }

        else if($filesize > 1024*1024*0.3){
            echo $name." is too big, can be a maximum of 3MB";
        }

        else{

            $image_path = 'images/' . substr(md5($name), 0, 10) . '.' . $image_extn;


            move_uploaded_file($image_temp, $image_path);

            mysql_query("INSERT INTO store VALUES ('', '$image_name', '$image_path')") or die(mysql_error());

            $lastid = mysql_insert_id();
            $image_link = mysql_query("SELECT * FROM store WHERE id = $lastid");
            $image_link = mysql_fetch_assoc($image_link);
            $image_link = $image_link['image'];
            echo "Image uploaded.<p></p> Your image: <p></p><a href = $image_link>$image_path</a>";
            }

        }
        }

    else{
            echo "Please select an image.";
        }

    ?>

4
  • I don't think it will ever be empty because it holds all the data for the upload. For example, it will tell you that the file size is 0. It will be a string of some sort - use print_r($_FILES) to check the array and see what you want to use to check if an image is not uploaded. Commented Sep 21, 2012 at 22:01
  • Try doing var_dump($_FILES) and viewing the contents... Commented Sep 21, 2012 at 22:02
  • What do you mean array is not empty ?? It should not be empty Commented Sep 21, 2012 at 22:03
  • Is this file named index.php? Commented Sep 21, 2012 at 22:03

9 Answers 9

19

This is how $_FILES array looks like when nothing uploaded

Array ( [image] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) )

So it's never empty.

The error code 4 [error] => 4 indicates no file was uploaded and error code 0 indicates no error and file was uploaded so you can check

if($_FILES['image']['error']==0) {
    // file uploaded, process code here
}

Here is another answer on SO.

Sign up to request clarification or add additional context in comments.

1 Comment

You can get different errors, I also see UPLOAD_ERR_PARTIAL (3) next to UPLOAD_ERR_NO_FILE (4).
8

Use the is_uploaded_file PHP function instead:

if(is_uploaded_file($_FILES['image']['tmp_name'])) {
  //code here
}

http://php.net/manual/en/function.is-uploaded-file.php

7 Comments

This worked when I put it under if(!empty($_FILES['image'])){ and used it as if(is_uploaded_file($_FILES['image']['tmp_name'][$count])) {.
Well, there are a thousand of other different things you could to as well, but this does not mean that it is actually the right way to do nor that you understand what you do. You need to check for the error code, see as well: php.net/manual/en/features.file-upload.errors.php - this become especially important with the $count you use here, because, well, you should better know with which kind of data you're working. See: php.net/manual/en/features.file-upload.post-method.php (uploading array of files)
This way worked fine. The only problem with I was having with the original code was when I submitted a blank form this code: ` else if(in_array($image_extn, $allowed) === false){ echo $name." is not an allowed file type<p></p>"; }` would still run.
Yes, sure. It works until it breaks. Question is if you're able to actually understand why something works and why not. I can only try to help you in the understanding. I added an answer that shows you what is actually going on, maybe it helps you to clarify things: stackoverflow.com/a/12538983/367456
I do understand what happened now. I was only checking if(!empty($_FILES['image'])){ to make sure the rest of the code involving the '$_FILES['image']' array was set otherwise an empty submitted form would return an array which would make this if(in_array($image_extn, $allowed) === false){ execute.
|
4

You should first of all take a look into the PHP manual because - you're not the first one with that problem - the solution has been written in there:

If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.

So if you actually want to find out if any file for the image element has has been submitted, check for it:

 $noFile = $_FILES['image']['size'][0] === 0 
           && $_FILES['image']['tmp_name'][0] === '';

Yes, that simple it is.

The test you used:

empty($_FILE);

will only tell you if the whole form has been submitted or not. So an example in full:

$submitted = empty($_FILE);
if ($submitted) {
    $noFile    = $_FILES['image']['size'][0] === 0 
                 && $_FILES['image']['tmp_name'][0] === '';
    if ($noFile) {
        ...
    }
}

2 Comments

You save a few bytes by using if(is_uploaded_file($_FILES['image']['tmp_name'])) resulting in a faster page load.. lol.
Sidenote: There might not be an error but the filesize is 0 bytes. That's a replay of the upload form w/o actually uploading any file-data. Can happen with browsers, I've seen it with Chromium.
2

Check value is not null:

in_array(!null,$_FILES['field_name']['name'])

Comments

2
if($_FILES['image']['error'] === UPLOAD_ERR_OK) {
    // Success code Goes here .. 
}

UPLOAD_ERR_OK returns value 0 if there is no error, the file was uploaded successfully.

Comments

1

http://php.net/manual/en/features.file-upload.post-method.php

If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.

You get an array entry per "file" upload field, even if the user didn't select a file to upload.

Comments

1

I have confronted this issue with a multiple file input. What I found to be working for checking if any file has been selected is:

<?php
$size_sum = array_sum($_FILES['img']['size']);
if ($size_sum > 0) {
 // at least one file has been uploaded
} else {
 // no file has been uploaded
}
?>

Comments

0
if(!empty($_FILES['image']['name'][0]) || !empty($_FILES['image']['name'][1]) ||  
!empty($_FILES['image']['name'][2]))

or

for($1=0;$i<count($_FILES['image']);$i++){
if(!empty($_FILES['image']['name'][$i])){
   // do something
}
}

Comments

-1
if(isset($_FILES['file'])){//do some thing here}

3 Comments

How is this code different from the other 6 answers? What is its goal? Please explain it in your answer.
i just shared the simple code that can be easily understand. i shared for beginners
You should add an explanation: how this code should be used?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.