Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 945
Ali Avatar asked Jun 03 '09 18:06

Ali


People also ask

How can I check if a file is uploaded in PHP?

The is_uploaded_file() function in PHP is an inbuilt function which is used to check whether the specified file uploaded via HTTP POST or not. The name of the file is sent as a parameter to the is_uploaded_file() function and it returns True if the file is uploaded via HTTP POST.

How do you check if file is uploaded or not?

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 .

Which function is used to determine whether a file was uploaded in PHP?

The is_uploaded_file() function checks whether the specified file is uploaded via HTTP POST.


2 Answers

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; } 
like image 90
karim79 Avatar answered Sep 28 '22 11:09

karim79


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     } } 
like image 37
pranjal Avatar answered Sep 28 '22 09:09

pranjal