Home  >  Article  >  Backend Development  >  How to Reliably Determine if a File Was Uploaded in PHP?

How to Reliably Determine if a File Was Uploaded in PHP?

DDD
DDDOriginal
2024-11-01 06:19:31823browse

How to Reliably Determine if a File Was Uploaded in PHP?

Evaluating User File Uploads in PHP

When validating user input, ensuring the integrity of file uploads is crucial. However, some forms may allow optional uploads. In such cases, skipping validation for users who haven't submitted files is essential.

Determining File Upload Presence

To check whether a file was uploaded, using $_FILES['myfile']['size'] <= 0 is not reliable. Instead, the is_uploaded_file() function offers a more accurate indicator.

Using is_uploaded_file()

<code class="php">if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
    echo 'No upload';
}

As the official documentation explains, this function:

  • Ensures that a file was uploaded via the HTTP POST method.
  • Protects against malicious attempts to access unintended files.

Sample Implementation

Consider this example from a FileUpload class:

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;
}

This method first checks if the $_FILES array is empty. If not, it retrieves the uploaded file and validates its existence using file_exists(). Finally, is_uploaded_file() confirms whether the file was actually uploaded.

The above is the detailed content of How to Reliably Determine if a File Was Uploaded in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn