只允许在上传过程中添加某些文件类型 [英] Only allow certain files types to be added during an upload

查看:26
本文介绍了只允许在上传过程中添加某些文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有,我正在使用以下代码将一些图片上传到我的 Wordpress 博客:

All, I'm using the following code to upload some images to my Wordpress blog:

$fieldname = 'logo';
include_once(ABSPATH . 'wp-admin/includes/media.php');
include_once(ABSPATH . 'wp-admin/includes/file.php');

if ($_FILES[$fieldname]) {
    $overrides = array('test_form' => false); 
    $file = wp_handle_upload($_FILES[$fieldname], $overrides);
    echo $file[error];
}

这很好用,但是我可以上传任何类型的文件,正如您所知,这可能有潜在危险.有没有办法确保文件只是覆盖中的 .jpg、.jpeg、.gif 或 .png 或类似的东西?任何帮助将不胜感激!

This works fine, however I can upload any type of file and as you are aware that could be potentially dangerous. Is there a way to make sure that the file is only a .jpg, .jpeg, .gif or a .png in the overrides or something like that?? Any help would be greatly appreciated!

谢谢!

推荐答案

在覆盖中为允许的 mime 类型设置一个数组.这是 gif/jpg 的示例

Set an array in your overrides for the mime types allowed. Here is an example for gif/jpg

$fieldname = 'logo';
include_once(ABSPATH . 'wp-admin/includes/media.php');
include_once(ABSPATH . 'wp-admin/includes/file.php');


if ($_FILES[$fieldname]) {
    $allowed_file_types = array('jpg' =>'image/jpg','jpeg' =>'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png');
    $overrides = array('test_form' => false, 'mimes' => $allowed_file_types);

    $file = wp_handle_upload($_FILES[$fieldname], $overrides);
    echo $file[error];
}

这篇关于只允许在上传过程中添加某些文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆