How to check if the user has selected a file to upload?

on the 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 that if users want to edit information WITHOUT loading a LOGO, an error occurs: "Error, you must load the desired type"

So, if the user did not put anything in the input field to load it, I do not want to enter these test conditions.

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

but both of them do not work.

Any ideas?

edit: maybe I wasn’t so clear, I don’t want to check if he uploaded the logo, I want to check if he chose the file to upload, because right now, if he doesn’t select the file to upload, php causes an error that says that it should load the desired format.

thank.

+44
file php upload
Jun 02 '10 at 13:33
source share
5 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 construct that only includes the upload / submit button when the upload field has a value other than an empty string ("") to avoid submitting the form without uploading at all.

+77
Jun 02 '10 at 14:27
source share

The php documentation contains a description of the file processing section. You find to check various errors, and one of them

 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 a code like

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

or

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

You should consider checking (and possibly providing an appropriate response for the user) for various other errors.

+32
Jun 02 '10 at 13:39
source share

You should use is_uploaded_file ($ _ FILES ['logo'] ['tmp_name']) to make sure the file is really uploaded via POST.

+14
Jun 02 '10 at 13:37
source share

I would check if ( file_exists ($_FILES['logo']['tmp_name'])) and see if it works.

Or, more appropriate (thanks to Baloo): if ( is_uploaded_file ($_FILES['logo']['tmp_name']))

+7
Jun 02 '10 at 13:37
source share
 if ($_FILES['logo']['error'] === 0) 

- the only right way

-3
Jun 02 '10 at 13:39
source share



All Articles