23

I am having a hard time using $_FILES

I want to check if file upload field is empty or not then apply a condition such that if file upload is empty then the script doesn't try uploading the file. How do I enforce this?

Cozy
  • 311
  • 5
  • 16
Mohamed Hassan
  • 1,579
  • 4
  • 19
  • 35

9 Answers9

43
if($_FILES["file"]["error"] != 0) {
//stands for any kind of errors happen during the uploading
} 

also there is

if($_FILES["file"]["error"] == 4) {
//means there is no file uploaded
}
Mohamed Hassan
  • 1,579
  • 4
  • 19
  • 35
21

This should work

if ( ! empty($_FILES)) {...}
Drazen
  • 2,776
  • 1
  • 25
  • 39
  • 1
    This worked for me to check wether the page has been called without posting a file. Most other solutions expect the 'file' index to be present and throw a notice. – Aviator Jun 29 '15 at 07:11
17

The other answers didn't work for me. So I post my solution:

if($_FILES['theFile']['name']=='')
{
    //No file selected
}
Alexandre Khoury
  • 3,896
  • 5
  • 37
  • 58
12

Here's what worked for me:

if ($_FILES['theFile']['tmp_name']!='') {
    // do this, upload file
} // if no file selected to upload, file isn't uploaded.
bash3r
  • 123
  • 1
  • 6
9

You can use the UPLOAD_ERR_NO_FILE value:

function isset_file($file) {
    return (isset($file) && $file['error'] != UPLOAD_ERR_NO_FILE);
}

if(isset_file($_FILES['input_name'])) {
    // It's not empty
}

Updated: Since sending $_FILES['input_name'] may throw a Notice

function isset_file($name) {
    return (isset($_FILES[$name]) && $_FILES[$name]['error'] != UPLOAD_ERR_NO_FILE);
}

if(isset_file('input_name')) {
    // It's not empty
}
lombervid
  • 136
  • 1
  • 3
3

this question is duplicate but your answer is is_uploade_file() function.

Amir
  • 2,149
  • 4
  • 23
  • 32
  • No. The function is to check whether the file is uploaded successfully, not check if empty. If the file is not empty but unable to upload (e.g. due to permission, file size restriction, etc.), the function still returns `false` (failure). – Raptor Oct 14 '19 at 09:50
2
if(!empty($_FILES['myFileField'])) {
    // file field is not empty..
} else {
    // no file uploaded..
}
evilReiko
  • 19,501
  • 24
  • 86
  • 102
2

To check if an input of type file is empty you will have to take any of $_FILES arrays and check it against an empty array. All that I have seen above is check against an empty string which will not work. Example:

if($_FILES["your_field_name"]["size"] == [' '])
{
Perform your validation here•
}

I hope this helps.

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
0

To check if a file content is empty(i.e you haven't select any file in the field ) by applying conditional statements. you can do it this way

if($_FILE['image']['size'][0] ==0){
     echo "No file selected";
}else{
     echo "You have select image";
}

hope this will help...

Code Explanation: it check if the file name of input and size at index 0 of the array is equal to zero