tags:

views:

109

answers:

1

I do some form validation to ensure that the file a user uploaded is of the right type. But the upload is optional, so i want to skip the validation if he didn't upload anything and submitted the rest of the form. How can I check if he uploaded something or not? Will $_FILES['myflie']['size'] <=0 work?

+3  A: 

You can use is_uploaded_file():

if(!file_exists($_FILES['myflie]['tmp_name']) || !is_uploaded_file($_FILES['myflie']['tmp_name'])) {
    echo 'No upload';
}

From the docs:

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

EDIT: I'm using this in my FileUpload class, in case it helps:

 public function fileUploaded()
        {
  if(empty($_FILES)) {
   return false;  
  } 
  $this->file = $_FILES[$this->formField];
  if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
   $this->errors['FileNotExists'] = true;
   return false;
  } 
  return true;
 }
karim79
Ayman, you need to give it the 'tmp_name'. From the doc:For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name']
karim79
Who downvoted this and *why* ?
karim79
@ Click Upvote - Added the file_exists() bit to the beginning, I'm actually using that, so I know it works. Give it a go.
karim79
My bad - the $_FILES array, as Greg B pointed out, should be checked with empty()
karim79
Actually it works, i had a bug earlier in my code which messed it a bit earlier
Click Upvote
@Click Upvote - aaaah, good to know I'm not insane :). Glad that fixed it for you.
karim79