Home >Backend Development >PHP Tutorial >How Can You Determine if a User Has Uploaded a File in PHP, Even if the Upload is Optional?
Checking User File Uploads in PHP
How can you determine if a user has uploaded a file in PHP, even if the upload is optional?
Solution:
1. Use is_uploaded_file()
To check if a file has been uploaded, use:
<code class="php">if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) { echo 'No upload'; }</code>
is_uploaded_file() ensures that the file was uploaded via HTTP POST and prevents malicious uploads.
2. FileUpload Class with FileUpload() Method
In a FileUpload class, you can implement the fileUploaded() method:
<code class="php">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; }</code>
This method checks if there are any files in the POST request and returns false if the file does not exist or is not uploaded. It sets an error flag if the file is missing and returns true if the file was successfully uploaded.
The above is the detailed content of How Can You Determine if a User Has Uploaded a File in PHP, Even if the Upload is Optional?. For more information, please follow other related articles on the PHP Chinese website!