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?
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.
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 .
The is_uploaded_file() function checks whether the specified file is uploaded via HTTP POST.
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; }
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With