0

I have this plugin im making and in the file upload system i have this:

$mimes = array('image/jpeg','image/jpg','image/gif','image/png','application/pdf');
if(in_array($_FILES['attach']['type'], $mimes)){
    $error = 0;
}
else {
    $error = 1;
}

Then, along with other error checking i have this to upload the files to a custom folder

if($error == 0) {
    $folder = PLUGIN_DIR . '/uploads/';
    if(is_dir($folder)) {
        $file = $_FILES["attach"]["tmp_name"];
        move_uploaded_file($file, $folder.date('Ymd').'_'.$name);
    }
}

This works perfectly. I've tested it but, is it ok to do like this? Or is there a better way to do it?

Thanks in advance!

0

WordPress has it's own way of handling file uploads, so it's best to follow their lead on that. It does do some file validation, but if you want to be restrictive with MIME types I'd keep the code you originally have,

Here's the code that can replace your second block though to actually upload the file (modified from an example in the Codex as linked above):

// Load in the file handler
    if ( ! function_exists( 'wp_handle_upload' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    }

// Change your upload directory
function wpse_271103_upload_dir(){
    return PLUGIN_DIR . '/uploads/';
}

// Register our path override.
add_filter( 'upload_dir', 'wpse_271103_upload_dir' );

// Set where to get the file from
$uploadedfile = $_FILES["attach"]["tmp_name"];

// Do the file move
$movefile = wp_handle_upload( $uploadedfile );

// Set everything back to normal.
remove_filter( 'upload_dir', 'wpse_271103_upload_dir' );

// Return an error if it couldn't be done
if ( ! $movefile || isset( $movefile['error'] ) ) {

    echo $movefile['error'];
}
  • thanks @stevenkellow. i'll try this =) but, what is the difference from move_uploaded_file() to wp_handle_upload()? is it more secure to use wp_handle_upload()? thanks – eskimopest Jun 23 '17 at 17:10
  • Yes wp_handle_upload does extra checks to sanitize the file names and check the MIME types as well to make sure nothing harmful gets uploaded. – stevenkellow Jun 23 '17 at 19:17
  • ok. tks. i'll give it a try ;) – eskimopest Jun 23 '17 at 19:35
  • just tested it. appears to have no errors but the file wont appear in the folder. can you give me a hand? tks =) – eskimopest Jun 26 '17 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.