6

I have an upload form with a file to be uploaded. The issue I have is that even when no file is uploaded the if(isset($_FILES)) OR if(!empty($_FILES)) still passes as successful:

$_FILES = $HTTP_POST_FILES;
if($_POST['type'] == 'photo' && isset($_FILES)){
// returns true even if no file is uploaded. What am I missing!
}
kalpaitch
  • 5,193
  • 10
  • 43
  • 67
  • Using `$HTTP_POST_FILES` is deprecated: http://php.net/manual/en/reserved.variables.files.php (besides that it contains the same values as `$_FILES`) – Felix Kling Mar 30 '10 at 22:07

1 Answers1

11

Being a superglobal, $_FILES is presumably always set, regardless whether an uploaded file exists or not.

Check for the file upload(s) you would expect and look at the size field. (Apparently according to the User Contributed Notes in the manual, if the form contains the upload element, it is possible that even isset($_FILES["my_file_name"]) will return true even though there was no file selected.

This should work reliably:

if($_POST['type'] == 'photo' && 
   ((isset($_FILES["my_file_name"]["size"]) && 
    ($_FILES["my_file_name"]["size"] > 0)) ){

(the isset() is to prevent a "undefined index" notice.)

What do you do this for, by the way?:

$_FILES = $HTTP_POST_FILES;
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • I did have this before but it was a bit longwided: $_FILES['image']['tmp_name']... You know I have no idea about that second line. $_FILES = $HTTP_POST_FILES; That was one of about three parts that was written by someone else. – kalpaitch Mar 30 '10 at 22:08
  • @kalpaitch I think you can safely remove that part, it was probably for backwards compatibility in PHP 4. – Pekka Mar 30 '10 at 22:09
  • @kalpaitch checking for tmp_name is also fine. – Pekka Mar 30 '10 at 22:09
  • @Pekka cheers for all that, its good to have that cleared up. – kalpaitch Mar 30 '10 at 22:13
  • @kalpaitch habit. I like having every single condition separated in a pair of brackets to avoid misunderstandings like `$x > 3 && $y < 3 + 1` but it's not necessary here, true. – Pekka Mar 30 '10 at 22:28