2

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;
}
  • Use 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 of upload_user_file() or before calling that func. – Samuel Elh May 27 '16 at 10:08
1

This is a full working example with file type and size limits and all the error handling.

Every step is commented. Let me know if you have any more questions.

  • You can find all the mime types from here.
  • Make sure to check if it's allowed in WP too.

// Allowed file types -> search online for desired mime types
$allowed_file_types = array( "image/jpeg", "image/jpg", "image/png" );
// Allowed file size -> 2MB
$allowed_file_size = 2000000;

$upload_errors = '';

// Check if has a file -> this assumes your file input "name" is "uploaded-file"
if ( ! empty( $_FILES['uploaded-file']['name'] ) ) {

    // Check file type
    if ( ! in_array( $_FILES['uploaded-file']['type'], $allowed_file_types ) ) {

        $upload_errors .= '<p>Invalid file type: ' . 
                          $_FILES['uploaded-file']['type'] . 
                          '. Supported file types: jpg, jpeg, png</p>';
    }

    // Check file size
    if ( $_FILES['uploaded-file']['size'] > $allowed_file_size ) {

        $upload_errors .= '<p>File is too large. Max. upload file size is 2MB</p>';
    }

    // No errors -> upload image
    if ( empty( $upload_errors ) ) {

        if ( $_FILES['uploaded-file']['error'] !== UPLOAD_ERR_OK ) __return_false();

        require_once( ABSPATH . 'wp-admin/includes/file.php' );

        // Upload the file -> if you don't want to attach it to post, pass $post_id as 0
        $upload_id = media_handle_upload( 'uploaded-file', $post_id );        

        if ( is_wp_error( $upload_id ) ) {

            // Error uploading the file -> show it
            echo '<p>Upload failed. Please submit again</p>';
        } 
        else {

            // No errors -> show success message
            echo '<p>Upload was successful</p>';
        }
    }

    // Had an error -> show error(s)    
    else {

        echo $upload_errors;
    }
}
0

You simply add an if statement like :

    if ( $file["type"] != "application/pdf" ){
        exit;
    }

You can add a message in $_SESSION and redirect the url to show for user what is wrong

if(session_id() == '') {
    session_start();
}
$_SESSION['error_uplaod'] = '.pdf with 2MB maxsize files is only allowed';
session_write_close();
wp_redirect( $_SERVER["REQUEST_URI"] );

in other way if you want to use $mimes :

function your_mimes($mimes) {
  $mimes = array('pdf' => 'application/pdf');
  return $mimes;
}

you can see list of all types : here then just before and after the upload method add :

add_filter('upload_mimes','your_mimes');

and :

remove_filter('upload_mimes','your_mimes');

if you leaved that with out remove it then thats will applied for all uploads in site after executing it .
Hope that help you

0
if ($_FILES['myfile']['size'] <= '2000000') {
    // if file size is not larger than 2MB
    $overrides['mimes'] = [
        'jpg|jpeg|jpe' => 'image/jpeg',
        'gif' => 'image/gif',
        'png' => 'image/png',
    ];
    $uploadResult = wp_handle_upload($_FILES['myfile'], $overrides);
    // use $uploadResult to continue working with your code.
} else {
    // if file size is larger than 2MB.
    // handle with the error below by yourself. it is just example.
    wp_die('Upload file size is too large.');
}

Reference: https://rundiz.com/?p=448

In mimes array key, you can use multiple file extensions but it must be able to use in regular expression.
From my example: jpg|jpeg|jpe means file extension can be one of these the | sign means OR and the array value is mime type.

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.