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

前端 未结 5 938
梦毁少年i
梦毁少年i 2020-11-28 08:52

on a page, i have :

if (!empty($_FILES[\'logo\'][\'name\'])) {
    $dossier     = \'upload/\';
    $fichier     = basename($_FILES[\'logo\'][\'name\']);
            


        
相关标签:
5条回答
  • 2020-11-28 09:31

    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.

    0 讨论(0)
  • 2020-11-28 09:38

    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.

    0 讨论(0)
  • 2020-11-28 09:52

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

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

    0 讨论(0)
  • 2020-11-28 09:52
    if ($_FILES['logo']['error'] === 0)
    

    is the only right way

    0 讨论(0)
  • 2020-11-28 09:55

    You should use is_uploaded_file($_FILES['logo']['tmp_name']) to make sure that the file was indeed uploaded through a POST.

    0 讨论(0)
提交回复
热议问题