I have a custom page template with a form, that any visitor of the website can upload a file. Now, I want to restrict the file type that will be upload (docx, doc and pdf only) and I limit the file size into 2MB only.
How to do this? I already have a function that the user allowed to upload, but I don't know how to restrict the file type that allowed to be upload. Please help me.
I tried to change
'post_mime_type' => $file_return['type']
into this
'post_mime_type' => 'application/msword,vnd.openxmlformats-officedocument.wordprocessingml.document,pdf'
but still it's not working.
PHP in custom page template
if(isset($_POST['submit'])){
$firstName = isset($_POST['firstName']) ? $_POST['firstName'] : '';
$middleName = isset($_POST['middleName']) ? $_POST['middleName'] : '';
$lastName = isset($_POST['lastName']) ? $_POST['lastName'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$mobile = isset($_POST['mobile']) ? $_POST['mobile'] : '';
$locations = isset($_POST['locations_list']) ? $_POST['locations_list'] : '';
$position = isset($_POST['position']) ? $_POST['position'] : '';
$message = isset($_POST['message']) ? $_POST['message'] : '';
if( ! empty($_FILES)){
$file=$_FILES['resumeFile'];
$attachment_id = upload_user_file($file);
}
$sql=$wpdb->query($wpdb->prepare("INSERT INTO resume_databank(submit_time,last_name,first_name,middle_name,mobile_number,email,location,position,message,process_resume,attachment_resume_id) VALUES (now(),'$lastName','$firstName','$middleName','$mobile','$email','$locations','$position','$message','No','$attachment_id')"));
}
PHP in functions.php
function upload_user_file($file = array()){
require_once(ABSPATH . 'wp-admin/includes/admin.php');
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment($attachment, $file_return['url']);
require_once(ABSPATH . 'wp-admin/includes/file.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
wp_update_attachment_metadata($attachment_id, $attachment_data);
if(0 < intval($attachment_id)){
return $attachment_id;
}
}
return false;
}
pathinfo(file_name)
to get the upload extension,$pathinfo = pathinfo( $file['name'] ); if( empty( $pathinfo ) || ! in_array( strtolower($pathinfo['extension']), array('jpg','bmp','png') ) ) { return; }
place it in the top ofupload_user_file()
or before calling that func.