钩子文档

wp_check_filetype_and_ext

💡 云策文档标注

概述

wp_check_filetype_and_ext 是一个 WordPress 过滤器,用于修改文件上传时的扩展名、MIME 类型和正确文件名。它允许开发者覆盖 PHP 的 finfo_file 函数检测结果,解决特定文件类型(如 CSV)被错误识别的问题。

关键要点

  • 过滤器名称:wp_check_filetype_and_ext,用于过滤文件的“真实”类型。
  • 参数:包括 $data(数组,包含 ext、type、proper_filename)、$file(文件路径)、$filename(文件名)、$mimes(MIME 类型数组)、$real_mime(实际 MIME 类型)。
  • 应用场景:常用于修正文件上传时的类型检测,例如确保 CSV 文件被正确识别为 text/csv,避免使用 ALLOW_UNFILTERED_UPLOADS 常量。
  • 版本历史:自 WordPress 3.0.0 引入,5.1.0 版本添加了 $real_mime 参数。

代码示例

add_filter( 'wp_check_filetype_and_ext', function ( $data, $file, $filename ) {
  // 获取上传文件的扩展名
  $ext = pathinfo( $filename, PATHINFO_EXTENSION );

  // 检查文件扩展名是否为 CSV
  if ( 'csv' === $ext ) {
      $data['ext']  = 'csv';
      $data['type'] = 'text/csv';
  }

  return $data;
}, 10, 3 );

注意事项

  • 使用此过滤器可以避免启用 ALLOW_UNFILTERED_UPLOADS,提高安全性。
  • 确保代码正确处理参数,特别是 $data 数组的键名(如 'ext' 和 'type')。

📄 原文内容

Filters the “real” file type of the given file.

Parameters

$wp_check_filetype_and_extarray
Values for the extension, mime type, and corrected filename.

  • ext string|false
    File extension, or false if the file doesn’t match a mime type.
  • type string|false
    File mime type, or false if the file doesn’t match a mime type.
  • proper_filename string|false
    File name with its correct extension, or false if it cannot be determined.

$filestring
Full path to the file.
$filenamestring
The name of the file (may differ from $file due to $file being in a tmp directory).
$mimesstring[]|null
Array of mime types keyed by their file extension regex, or null if none were provided.
$real_mimestring|false
The actual mime type or false if the type cannot be determined.

Source

return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes, $real_mime );

Changelog

Version Description
5.1.0 The $real_mime parameter was added.
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    You will want to use this filter as the function finfo_file from PHP doesn’t always detect CSV files as text/plain or text/csv, instead it is tagged as application/octet-stream.

    This creates a problem since WordPress will not allow you to upload the file to the library or even WooCommerce import and therefore you can use the filter as follows.

    The following code will help avoid using ALLOW_UNFILTERED_UPLOADS when all you need to enable is one file type.

    add_filter( 'wp_check_filetype_and_ext', function ( $data, $file, $filename ) {
      // Get the extension of the uploaded file
      $ext = pathinfo( $filename, PATHINFO_EXTENSION );
    
      // Check if the file extension is CSV
      if ( 'csv' === $ext ) {
          $data[‘ext’]  = 'csv';
          $data[‘type’] = 'text/csv';
      }
    
      return $data;
    }, 10, 3 );