【问题标题】:limit file size for jpg and pdf uploads限制 jpg 和 pdf 上传的文件大小
【发布时间】:2020-01-05 02:36:08
【问题描述】:

我不精通 php,但我发现了一个 sn-p,它会限制我的用户将大于 1mb 的“图像”文件上传到我的 wordpress 网站。 (我将编辑此限制以满足我的要求)。 我假设“图像”文件是 jpg、png 等。 但是 pdf 文件呢,这个 sn-p 是否也会限制它们,或者它们不被归类为“图像”类型的文件?

理想情况下,我需要限制 jpg 和 pdf 文件。这个需要修改吗?

// WP - LIMIT IMAGE UPLOAD SIZE
function max_image_size( $file ) {
$size = $file['size'];
$size = $size / 1024;
$type = $file['type'];
$is_image = strpos( $type, 'image' ) !== false;
$limit = 1024;  
$limit_output = '1MB';
if ( $is_image && $size > $limit ) {
$file['error'] = 'Image files must be smaller than ' . $limit_output;
}//end if
return $file;
}//end max_image_size()
add_filter( 'wp_handle_upload_prefilter', 'max_image_size' );

( 使用 php 7.2 ) 提前致谢, 克里斯。

【问题讨论】:

  • 不——这只是必要检查的一部分(过滤器)。它分析一个 $file 并返回一个可能的错误消息作为 $file-array 的一部分。您也需要上传文件的部分。标准方法是上传文件,然后检查是否要保留数据。最后 - 不,不包括 PDF。
  • 谢谢,我已将此添加到我的子主题 (functions.php) 中,它适用于图像文件限制。我应该提到这一点,抱歉。

标签: php upload-max-filesize


【解决方案1】:

如果要限制所有资源替换:

if ( $is_image && $size > $limit ) {
  $file['error'] = 'Image files must be smaller than ' . $limit_output;
}//end if

与:

if ( $size > $limit ) {
  $file['error'] = 'Files must be smaller than ' . $limit_output;
}//end if

可选[1]:您可以将 max_image_size 函数重命名为 max_file_size 并将 addfilter 更改为 add_filter( 'wp_handle_upload_prefilter', 'max_file_size' );

可选[2]:您可以使用以下方法检测PDF mime类型,即application/pdf:

$is_pdf = strpos( $type, 'pdf' ) !== false;

并添加其他条件:

if ( $is_image && $size > $limit ) {
  $file['error'] = 'Image files must be smaller than ' . $limit_output;
}//end if
if ( $is_pdf && $size > $limit ) {
  $file['error'] = 'PDF files must be smaller than ' . $limit_output;
}//end if

【讨论】:

  • 谢谢,我会尝试上述解决方案。第一个解决方案是否意味着我可以从原始 sn-p 中省略以下两行,因为它们标识了不再需要的文件类型? $type = $file['type']; $is_image = strpos( $type, 'image' ) !== false;另外,只是为了检查一下,这是否只会限制前端上传,而不是阻止我以管理员身份添加更大的文件?或插件等...
猜你喜欢
  • 1970-01-01
  • 2022-10-26
  • 2016-08-22
  • 1970-01-01
  • 2013-10-19
  • 2011-01-29
  • 2017-03-09
  • 2011-01-13
  • 1970-01-01
相关资源
最近更新 更多