Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a user has SELECTED a file to upload?

Tags:

file

php

upload

on a page, i have :

if (!empty($_FILES['logo']['name'])) {     $dossier     = 'upload/';     $fichier     = basename($_FILES['logo']['name']);     $taille_maxi = 100000;     $taille      = filesize($_FILES['logo']['tmp_name']);     $extensions  = array('.png', '.jpg', '.jpeg');     $extension   = strrchr($_FILES['logo']['name'], '.');      if(!in_array($extension, $extensions)) {         $erreur = 'ERROR you  must upload the right type';     }      if($taille>$taille_maxi) {          $erreur = 'too heavy';     }      if(!empty($erreur)) {       // ...     } } 

The problem is, if the users wants to edit information WITHOUT uploading a LOGO, it raises an error : 'error you must upload the right type'

So, if a user didn't put anything in the inputbox in order to upload it, i don't want to enter in these conditions test.

i tested : if (!empty($_FILES['logo']['name']) and if (isset($_FILES['logo']['name'])

but both doesn't seems to work.

Any ideas?

edit : maybe i wasn't so clear, i don't want to test if he uploaded a logo, i want to test IF he selected a file to upload, because right now, if he doesn't select a file to upload, php raises an error telling he must upload with the right format.

thanks.

like image 751
sf_tristanb Avatar asked Jun 02 '10 13:06

sf_tristanb


People also ask

How do you check if a file is selected or not?

length property to check file is selected or not. If element. files. length property returns 0 then the file is not selected otherwise file is selected.

How check file is selected or not in PHP?

To check whether any file is existing or not then we can use the below-mentioned PHP function. To find the existence of the files, we use file_exists() function. This function is used to check whether a file or directory exists or not.


2 Answers

You can check this with:

if (empty($_FILES['logo']['name'])) {     // No file was selected for upload, your (re)action goes here } 

Or you can use a javascript construction that only enables the upload/submit button whenever the upload field has a value other then an empty string ("") to avoid submission of the form with no upload at all.

like image 150
Oldskool Avatar answered Sep 22 '22 09:09

Oldskool


There is a section in php documentation about file handling. You will find that you can check various errors and one of them is

UPLOAD_ERR_OK     Value: 0; There is no error, the file uploaded with success. <...> UPLOAD_ERR_NO_FILE     Value: 4; No file was uploaded. 

In your case you need code like

if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) { ... } 

or

if ($_FILES['logo']['error'] != UPLOAD_ERR_NO_FILE) { ... } 

You should consider checking (and probably providing appropriate response for a user) for other various errors as well.

like image 45
Jonas Avatar answered Sep 19 '22 09:09

Jonas