【问题标题】:How to check whether the user uploaded a file in PHP?如何检查用户是否在PHP中上传了文件?
【发布时间】:2009-06-03 18:38:53
【问题描述】:

我会进行一些表单验证以确保用户上传的文件类型正确。但是上传是可选的,所以如果他没有上传任何东西并提交了表单的其余部分,我想跳过验证。我怎样才能检查他是否上传了一些东西? $_FILES['myflie']['size'] <=0 会起作用吗?

【问题讨论】:

    标签: php


    【解决方案1】:

    你可以使用is_uploaded_file():

    if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
        echo 'No upload';
    }
    

    来自文档:

    如果文件名为 文件名是通过 HTTP POST 上传的。 这有助于确保 恶意用户没有试图欺骗 脚本开始处理文件 它不应该为它工作 例如,/etc/passwd。

    这种检查尤其 重要的是,如果有任何机会 对上传的文件所做的任何事情 可以将其内容透露给 用户,甚至是其他用户 同一个系统。

    编辑:我在我的 FileUpload 类中使用它,以防它有帮助:

    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;
    }
    

    【讨论】:

    • Ayman,你需要给它'tmp_name'。来自文档:为了正常工作,函数 is_uploaded_file() 需要一个参数,如 $_FILES['userfile']['tmp_name']
    • @Click Upvote - 在开头添加了 file_exists() 位,我实际上正在使用它,所以我知道它有效。试一试。
    • 我的错 - 正如 Greg B 指出的,$_FILES 数组应该用 empty() 检查
    • 实际上它可以工作,我的代码之前有一个错误,它更早地搞砸了
    • 请注意,如果您使用的是数组,例如name=files[] 这会导致错误 file_exists() expects parameter 1 to be a valid path, array given 您必须更深入地查看 $_FILES['files']['tmp_name'][0] 是否为空/已上传。
    【解决方案2】:

    这段代码对我有用。我正在使用多个文件上传,所以我需要检查是否有任何上传。

    HTML 部分:

    <input name="files[]" type="file" multiple="multiple" />
    

    PHP部分:

    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
        }
    }
    

    【讨论】:

      【解决方案3】:

      @karim79 有正确的答案,但我不得不重写他的例子以适应我的目的。他的示例假设提交字段的名称是已知的并且可以硬编码。我更进一步并创建了一个函数,它可以告诉我是否上传了任何文件,而无需知道上传字段的名称。

      /**
       * Tests all upload fields to determine whether any files were submitted.
       * 
       * @return boolean
       */
      function files_uploaded() {
      
          // bail if there were no upload forms
         if(empty($_FILES))
              return false;
      
          // check for uploaded files
          $files = $_FILES['files']['tmp_name'];
          foreach( $files as $field_title => $temp_name ){
              if( !empty($temp_name) && is_uploaded_file( $temp_name )){
                  // found one!
                  return true;
              }
          }   
          // return false if no files were found
         return false;
      }
      

      【讨论】:

      • 对我来说,除非提交字段的名称是“文件”,否则这不起作用。我不得不将$files = $_FILES['files']['tmp_name']; foreach( $files as $field_title =&gt; $temp_name ){ 行替换为foreach( $_FILES as $field_title =&gt; $file ) { $temp_name = $file['tmp_name'];
      【解决方案4】:

      您应该使用$_FILES[$form_name]['error']。如果没有上传文件,则返回 UPLOAD_ERR_NO_FILE。完整名单:PHP: Error Messages Explained

      function isUploadOkay($form_name, &$error_message) {
          if (!isset($_FILES[$form_name])) {
              $error_message = "No file upload with name '$form_name' in form.";
              return false;
          }
          $error = $_FILES[$form_name]['error'];
      
          // List at: http://php.net/manual/en/features.file-upload.errors.php
          if ($error != UPLOAD_ERR_OK) {
              switch ($error) {
                  case UPLOAD_ERR_INI_SIZE:
                      $error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
                      break;
      
                  case UPLOAD_ERR_FORM_SIZE:
                      $error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
                      break;
      
                  case UPLOAD_ERR_PARTIAL:
                      $error_message = 'The uploaded file was only partially uploaded.';
                      break;
      
                  case UPLOAD_ERR_NO_FILE:
                      $error_message = 'No file was uploaded.';
                      break;
      
                  case UPLOAD_ERR_NO_TMP_DIR:
                      $error_message = 'Missing a temporary folder.';
                      break;
      
                  case UPLOAD_ERR_CANT_WRITE:
                      $error_message = 'Failed to write file to disk.';
                      break;
      
                  case UPLOAD_ERR_EXTENSION:
                      $error_message = 'A PHP extension interrupted the upload.';
                      break;
      
                  default:
                      $error_message = 'Unknown error';
                  break;
              }
              return false;
          }
      
          $error_message = null;
          return true;
      }
      

      【讨论】:

        【解决方案5】:
        <!DOCTYPE html>
        <html>
        <body>
        
        <form action="#" method="post" enctype="multipart/form-data">
            Select image to upload:
            <input name="my_files[]" type="file" multiple="multiple" />
            <input type="submit" value="Upload Image" name="submit">
        </form>
        
        
        <?php
        
         if (isset($_FILES['my_files']))
          {
            $myFile = $_FILES['my_files'];
            $fileCount = count($myFile["name"]);
        
        
                for ($i = 0; $i <$fileCount; $i++)
                 {
                   $error = $myFile["error"][$i]; 
        
                    if ($error == '4')  // error 4 is for "no file selected"
                     {
                       echo "no file selected";
                     }
                    else
                     {
        
                       $name =  $myFile["name"][$i];
                       echo $name; 
                       echo "<br>"; 
                       $temporary_file = $myFile["tmp_name"][$i];
                       echo $temporary_file;
                       echo "<br>";
                       $type = $myFile["type"][$i];
                       echo $type;
                       echo "<br>";
                       $size = $myFile["size"][$i];
                       echo $size;
                       echo "<br>";
        
        
        
                       $target_path = "uploads/$name";   //first make a folder named "uploads" where you will upload files
        
        
                         if(move_uploaded_file($temporary_file,$target_path))
                          {
                           echo " uploaded";
                           echo "<br>";
                           echo "<br>";
                          }
                           else
                          {
                           echo "no upload ";
                          }
        
        
        
        
                      }
                }  
        }
                ?>
        
        
        </body>
        </html>
        

        但要保持警惕。用户可以上传任何类型的文件,也可以通过上传恶意或 php 文件来破解您的服务器或系统。在这个脚本中应该有一些验证。谢谢。

        【讨论】:

          【解决方案6】:

          is_uploaded_file()很好用,专门用来检查是上传文件还是本地文件(出于安全考虑)。

          但是,如果要检查用户是否上传了文件, 使用$_FILES['file']['error'] == UPLOAD_ERR_OK

          请参阅file upload error messages 上的 PHP 手册。如果您只想检查没有文件,请使用UPLOAD_ERR_NO_FILE

          【讨论】:

            【解决方案7】:

            我检查了你的代码,认为你应该试试这个:

            if(!file_exists($_FILES['fileupload']['tmp_name']) || !is_uploaded_file($_FILES['fileupload']['tmp_name'])) 
                {
                    echo 'No upload';
                }   
                else
                    echo 'upload';
            

            【讨论】:

              【解决方案8】:

              一般情况下,当用户上传文件时,PHP服务器没有捕捉到任何异常错误或错误,说明文件上传成功。 https://www.php.net/manual/en/reserved.variables.files.php#109648

              if ( boolval( $_FILES['image']['error'] === 0 ) ) {
                  // ...
              }
              

              【讨论】:

                猜你喜欢
                • 2013-07-18
                • 2016-02-15
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-11-02
                • 2019-05-23
                相关资源
                最近更新 更多