Home >Backend Development >PHP Tutorial >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:
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!