1

I'm writing a script to handle a file upload. I've got the script in place, validating and uploading correctly.

But....the upload is optional. When I submit the form, the $_FILES['field_name'] is always present which consequently forces my validation to kick in.

How can I detect if there is a file upload or not?

2
  • The reason why you have value is because the browser send the value of all form elements: if empty, it will still send empty value. You can "solve" this by simple JavaScript that upon submit will remove empty elements from the form, let me know if you're interested. Commented Dec 9, 2010 at 11:17
  • 1
    (related) Unit-Testing File Uploads with PHP
    – Gordon
    Commented Dec 9, 2010 at 11:18

4 Answers 4

1

Take a look at is_uploaded_file.

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
   echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
}
0
0

You could use :

if (!empty($_FILES['file']['name'])) {
}

Which amounts to (almost) the same as the other answers on here.

0

I use:

if(isset($_FILES['file']) && $_FILES['file']['name'] != '') {

Where 'file' is the name of your file field.

0
    if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
// Code goes here
}