如何防止上传BMP图像?

时间:2010-11-16 作者:mha

我需要阻止为用户上载bmp图像。怎么可能呢?

2 个回复
最合适的回答,由SO网友:mha 整理而成

I have found the solution from here. And its working!

WordPress has a set of restricted filetypes it will allow you to upload via the media library. Whilst this is a great security feature, there may be times where you’d like to add other files that are restricted by default, or maybe even the opposite where you’d only like to allow a few extensions to be uploaded. Fortunately, WordPress makes this dead easy with a small snippet of PHP code.

If you’d like to add or remove a specific filetype that can be uploaded to wordpress via the media library, you can insert this PHP code in your theme functions.php file:


function my_myme_types($mime_types){
//Adjust the $mime_types, which is an associative array
//where the key is extension and value is mime type.
    return $mime_types;
}
add_filter(\'upload_mimes\', \'my_myme_types\', 1, 1);

Here is an example of what you can do to add and remove a new filetype (in this example, I’m adding an extension that already exists, but the concept is the same):


function my_myme_types($mime_types){
    $mime_types[\'avi\'] = \'video/avi\'; //Adding avi extension
    unset($mime_types[\'pdf\']); //Removing the pdf extension
    return $mime_types;
}
add_filter(\'upload_mimes\', \'my_myme_types\', 1, 1);

You can also reset the allowed filetypes by creating a new array within the function and returning these values:


function my_myme_types($mime_types){
    //Creating a new array will reset the allowed filetypes
    $mime_types = array(
        \'jpg|jpeg|jpe\' => \'image/jpeg\',
        \'gif\' => \'image/gif\',
        \'png\' => \'image/png\',
        \'bmp\' => \'image/bmp\',
        \'tif|tiff\' => \'image/tiff\'
    );
    return $mime_types;
}
add_filter(\'upload_mimes\', \'my_myme_types\', 1, 1);

If you’d like to see what filetypes are currently supported by wordpress, check out the function get_allowed_mime_types located in the wp-includes/functions.php file.

SO网友:hakre

魔力在于get_allowed_mime_types() 这就叫upload_mimes 滤器这将筛选默认数组,该数组由键组成,作为文件扩展名的非终止正则表达式,并将映射的mime类型作为值:

array(
    \'jpg|jpeg|jpe\' => \'image/jpeg\',
    \'gif\' => \'image/gif\',
    \'png\' => \'image/png\',
    \'bmp\' => \'image/bmp\',
    \'tif|tiff\' => \'image/tiff\',
    \'ico\' => \'image/x-icon\',
    ....
}
所以挂上过滤器并移除bmp 目前应做好以下工作:

/** prevent uploading of .bmp files. */
add_filter(\'upload_mimes\', function(array $mimes)
    { 
        unset($mimes[\'bmp\']);
        return $mimes;
    })
    ;
把它复制到一个名为no-bmp-upload.php 并将其放入wp-content\\mu-plugins 文件夹

结束

相关推荐

404从wp-Content/Uploads/获取图像时

我在获取图像时获得404状态,http仍然包含该图像。图像显示在浏览器中,但404代码中断了一些应用程序。对wp内容/上载/的调用被重定向到。htaccess:<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\\.php$ - [L] RewriteRule (.*) /index.php?getfile=$1 [L] </IfModule>&