How to check whether the user uploaded a file in 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;
}

Leave a Comment