我制作了这个插件,在文件上传系统中我有:
$mimes = array(\'image/jpeg\',\'image/jpg\',\'image/gif\',\'image/png\',\'application/pdf\');
if(in_array($_FILES[\'attach\'][\'type\'], $mimes)){
$error = 0;
}
else {
$error = 1;
}
然后,连同其他错误检查,我有这个上传文件到一个自定义文件夹
if($error == 0) {
$folder = PLUGIN_DIR . \'/uploads/\';
if(is_dir($folder)) {
$file = $_FILES["attach"]["tmp_name"];
move_uploaded_file($file, $folder.date(\'Ymd\').\'_\'.$name);
}
}
这非常有效。我已经测试过了,但这样可以吗?还是有更好的方法?
提前感谢!
SO网友:stevenkellow
WordPress has it\'s own way of handling file uploads, 因此,在这方面最好跟随他们的领导。它确实会进行一些文件验证,但如果您想限制MIME类型,我会保留您原来的代码,
下面的代码可以代替您的第二个块,但实际上载文件(根据上文链接的Codex中的示例进行修改):
// 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\'];
}