3

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];
}

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!

Thanks!

user1048676
  • 9,756
  • 26
  • 83
  • 120

2 Answers2

9

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/jpeg',
        '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];
}
MTpH9
  • 304
  • 2
  • 10
David Houde
  • 4,835
  • 1
  • 20
  • 29
  • 1
    Thanks, this is what I was looking for. It gives me an error though when I try and upload an image saying that it isn't allowed. Any idea on how I can see the value that it's checking against? – user1048676 Mar 09 '12 at 19:36
0

You could check on file extension like this:

    // check for extension !
    $name = $_FILES['foto']['name'];
    $ext = explode(".",$name);
    $ext = array_reverse($ext);
    $ext = strtolower($ext[0]);
    $valid = 0;
    $error = false;

    if (!empty($_GET['exts'])) {
        if ($_GET['exts'] == 'all') {
            $valid=1;
        } else {
            if (strpos($_GET['exts'],$ext) !== false) $valid=1;
            else $valid=0;
        }
    } else {
        if (strpos($defexts,$ext) !== false) $valid=1;
        else $valid=0;
    }

You can also check for the mime type of the file, which is value 'type' instead of 'name'. See http://www.php.net/manual/en/reserved.variables.files.php

Steven De Groote
  • 2,187
  • 5
  • 32
  • 52