【问题标题】:Php file upload, check file typephp文件上传,检查文件类型
【发布时间】:2017-05-06 16:58:00
【问题描述】:

我有这个代码,我用来上传多个文件。

    if(isset($_POST['submitButton']))
{
    if(isset($_FILES['gallery']))
    {
        if($_FILES["gallery"]["size"] > 0 )
        {
            foreach($_FILES['gallery']["name"] AS $key=>$file)
            {
                if($_FILES['gallery']['size'][$key]  != 0 )
                {
                    $target_path = "../documents/" . date( "Y-m-d" ) . '-' . rand(10, 999999999) . '-' . $_FILES['gallery']['name'][$key];
                    $fajl_nev = mysqli_real_escape_string($kapcs,  $_POST["images_alt"][ $key ] );                  
                    if(move_uploaded_file( $_FILES['gallery']['tmp_name'][$key], $target_path ))
                    {
                        $file_name = basename($target_path);
                        $sql = 
                        "
                            INSERT INTO letoltheto_fajl
                            (
                                fajl_nev,
                                fajl_file,
                                fajl_datetime
                            )
                            VALUES
                            (
                                '$fajl_nev',
                                '$file_name',
                                NOW()
                            )
                        ";
                        mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
                        header("Location: ".$host."/".$admin_folder."/feltoltott-fajlok.php?new=1");
                    }
                    else
                    {
                        $error[] = "A fájl feltöltése nem sikerült, próbálja újra.";
                    }
                }
            }
        }
    }
}

如何查看文件类型?我在下面的数组中给出了允许的文件类型:

    $allowed_files = array
(
    "image/jpg", 
    "image/jpeg", 
    "image/bmp", 
    "image/gif",
    "image/png",
    "application/pdf"
);

而且我还想允许更多文件,例如 excel、word...我怎样才能提供这些类型?有什么内容,我可以在哪里阅读?

【问题讨论】:

标签: php file file-upload


【解决方案1】:

您想检查文件扩展名或 mime。试试这样的:

$allowedFiles =  array('gif', 'png', 'jpg', 'jpeg, 'bmp', 'pdf', 'doc', 'docx'); // etc...
$filename = $_FILES['gallery']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext, $allowedFiles) ) {
    echo 'Error...';
}

【讨论】:

    【解决方案2】:

    txt 不在允许列表中,它还可以让我上传 txt 文件。

    $allowed_files = array
    

    ( // 图片 'png' => '图像/png', 'jpe' => '图像/jpeg', 'jpeg' => '图像/jpeg', 'jpg' => '图像/jpeg', 'gif' => '图像/gif', 'bmp' => '图像/bmp',

    // PDF files
    'pdf'  => 'application/pdf',
    
    // Tömörített fájlok
    'zip'  => 'application/zip',
    'rar'  => 'application/x-rar-compressed',
    
    // MS office
    'doc'  => 'application/msword',
    'rtf'  => 'application/rtf',
    'xls'  => 'application/vnd.ms-excel',
    'ppt'  => 'application/vnd.ms-powerpoint',
    
    // Open Office
    'odt'  => 'application/vnd.oasis.opendocument.text',
    'ods'  => 'application/vnd.oasis.opendocument.spreadsheet'
    

    );

    if(isset($_POST['submitButton']))
    {
        if(isset($_FILES['gallery']))
        {
            if($_FILES["gallery"]["size"] > 0 )
            {
                foreach($_FILES['gallery']["name"] AS $key=>$file)
                {
                    if($_FILES['gallery']['size'][$key]  != 0 )
                    {
    
                        $filename = $_FILES['gallery']['name'][$key];
                        $ext = pathinfo($filename, PATHINFO_EXTENSION);
                        if(!in_array($ext, $allowed_files[0]) ) 
                        {
                            $error[] = "Nem engedélyezett fájl típus.";
                        }
    
                        $target_path = "../documents/" . date( "Y-m-d" ) . '-' . rand(10, 999999999) . '-' . $_FILES['gallery']['name'][$key];
                        $fajl_nev = mysqli_real_escape_string($kapcs,  $_POST["images_alt"][ $key ] );                  
                        if(move_uploaded_file( $_FILES['gallery']['tmp_name'][$key], $target_path ))
                        {
                            $file_name = basename($target_path);
                            $sql = 
                            "
                                INSERT INTO letoltheto_fajl
                                (
                                    fajl_nev,
                                    fajl_file,
                                    fajl_datetime
                                )
                                VALUES
                                (
                                    '$fajl_nev',
                                    '$file_name',
                                    NOW()
                                )
                            ";
                            mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
                            header("Location: ".$host."/".$admin_folder."/feltoltott-fajlok.php?new=1");
                        }
                        else
                        {
                            $error[] = "A fájl feltöltése nem sikerült, próbálja újra.";
                        }
                    }
                }
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      您需要从文件内容而不是客户端 mimetype 中获取文件类型。

      if(in_array(mime_type($file_path),$allowed_mime_types)){
          // save the file
      }
      
      $allowed_mime_types = array(
              'image/jpeg',
              'image/jpg',
              'image/png',
              'image/gif',
              'video/mp4'
      );
      
      
      /*
      For PHP>=5.3.0, you can use php's `finfo_file`([finfo_file](https://www.php.net/manual/en/function.finfo-file.php)) function to get the file infomation about the file.
      
      For PHP<5.3.0, you can use your's system's `file` command to get the file information.
      */
      function mime_type($file_path)
      {
          if (function_exists('finfo_open')) {            
              $finfo = new finfo(FILEINFO_MIME_TYPE, null);
              $mime_type = $finfo->file($file_path);
          }
          if (!$mime_type && function_exists('passthru') && function_exists('escapeshellarg')) {
              ob_start();
              passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($file_path)), $return);
              if ($return > 0) {
                  ob_end_clean();
                  $mime_type = null;
              }
              $type = trim(ob_get_clean());
              if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
                  $mime_type = null;
              }
              $mime_type = $match[1];
          }
          return $mime_type;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-23
        • 2012-01-29
        • 1970-01-01
        • 2011-08-02
        • 2011-10-08
        • 1970-01-01
        • 2012-09-16
        • 2016-01-25
        相关资源
        最近更新 更多