How to check whether the user uploaded a file in PHP?

Php

Php Problem Overview


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 whether he uploaded something or not? Will $_FILES['myflie']['size'] <=0 work?

Php Solutions


Solution 1 - Php

You can use is_uploaded_file():

if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['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;
}

Solution 2 - Php

This code worked for me. I am using multiple file uploads so I needed to check whether there has been any upload.

HTML part:

<input name="files[]" type="file" multiple="multiple" />

PHP part:

if(isset($_FILES['files']) ){  


foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){

      if(!empty($_FILES['files']['tmp_name'][$key])){

    //	things you want to do
    }
}

Solution 3 - Php

@karim79 has the right answer, but I had to rewrite his example to suit my purposes. His example assumes that the name of the submitted field is known and can be hard coded in. I took that a step further and made a function that will tell me if any files were uploaded without having to know the name of the upload field.

/**
 * Tests all upload fields to determine whether any files were submitted.
 * 
 * @return boolean
 */
function files_uploaded() {
	
	// bail if there were no upload forms
   if(empty($_FILES))
		return false;
   
	// check for uploaded files
	$files = $_FILES['files']['tmp_name'];
	foreach( $files as $field_title => $temp_name ){
		if( !empty($temp_name) && is_uploaded_file( $temp_name )){
			// found one!
			return true;
		}
	}	
	// return false if no files were found
   return false;
}

Solution 4 - Php

<!DOCTYPE html>
<html>
<body>

<form action="#" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input name="my_files[]" type="file" multiple="multiple" />
    <input type="submit" value="Upload Image" name="submit">
</form>


<?php
    
 if (isset($_FILES['my_files']))
  {
    $myFile = $_FILES['my_files'];
    $fileCount = count($myFile["name"]);
       
    
        for ($i = 0; $i <$fileCount; $i++)
         {
           $error = $myFile["error"][$i]; 
           
            if ($error == '4')  // error 4 is for "no file selected"
             {
               echo "no file selected";
             }
            else
             {
               
               $name =  $myFile["name"][$i];
               echo $name; 
               echo "<br>"; 
               $temporary_file = $myFile["tmp_name"][$i];
               echo $temporary_file;
               echo "<br>";
               $type = $myFile["type"][$i];
               echo $type;
               echo "<br>";
               $size = $myFile["size"][$i];
               echo $size;
               echo "<br>";
               

              
               $target_path = "uploads/$name";   //first make a folder named "uploads" where you will upload files

            
                 if(move_uploaded_file($temporary_file,$target_path))
                  {
                   echo " uploaded";
                   echo "<br>";
                   echo "<br>";
                  }
                   else
                  {
                   echo "no upload ";
                  }




              }
        }  
}
        ?>


</body>
</html>

But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations. Thank you.

Solution 5 - Php

You should use $_FILES[$form_name]['error']. It returns UPLOAD_ERR_NO_FILE if no file was uploaded. Full list: PHP: Error Messages Explained

function isUploadOkay($form_name, &$error_message) {
    if (!isset($_FILES[$form_name])) {
        $error_message = "No file upload with name '$form_name' in form.";
        return false;
    }
    $error = $_FILES[$form_name]['error'];

    // List at: http://php.net/manual/en/features.file-upload.errors.php
    if ($error != UPLOAD_ERR_OK) {
        switch ($error) {
            case UPLOAD_ERR_INI_SIZE:
                $error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
                break;
            
            case UPLOAD_ERR_FORM_SIZE:
                $error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
                break;

            case UPLOAD_ERR_PARTIAL:
                $error_message = 'The uploaded file was only partially uploaded.';
                break;

            case UPLOAD_ERR_NO_FILE:
                $error_message = 'No file was uploaded.';
                break;

            case UPLOAD_ERR_NO_TMP_DIR:
                $error_message = 'Missing a temporary folder.';
                break;

            case UPLOAD_ERR_CANT_WRITE:
                $error_message = 'Failed to write file to disk.';
                break;

            case UPLOAD_ERR_EXTENSION:
                $error_message = 'A PHP extension interrupted the upload.';
                break;

            default:
                $error_message = 'Unknown error';
            break;
        }
        return false;
    }

    $error_message = null;
    return true;
}

Solution 6 - Php

I checked your code and think you should try this:

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

Solution 7 - Php

is_uploaded_file() is great to use, specially for checking whether it is an uploaded file or a local file (for security purposes).

However, if you want to check whether the user uploaded a file, use $_FILES['file']['error'] == UPLOAD_ERR_OK.

See the PHP manual on file upload error messages. If you just want to check for no file, use UPLOAD_ERR_NO_FILE.

Solution 8 - Php

In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully. https://www.php.net/manual/en/reserved.variables.files.php#109648

if ( boolval( $_FILES['image']['error'] === 0 ) ) {
    // ...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAliView Question on Stackoverflow
Solution 1 - Phpkarim79View Answer on Stackoverflow
Solution 2 - PhppranjalView Answer on Stackoverflow
Solution 3 - Phpdoub1ejackView Answer on Stackoverflow
Solution 4 - PhpshivView Answer on Stackoverflow
Solution 5 - PhpSimon BackxView Answer on Stackoverflow
Solution 6 - PhpGauravView Answer on Stackoverflow
Solution 7 - PhpTD_NijboerView Answer on Stackoverflow
Solution 8 - PhpOussama ANDALOUSSIView Answer on Stackoverflow