I am trying to allow CSV files in a dashboard menu page like this..

<form method="post" enctype="multipart/form-data">
    <input type="file" name="csv_file" id="csv_file"  multiple="false" accept=".csv" />
    <input type="submit" value="Upload" />
</form>


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

$attachment_id = media_handle_upload ( 'csv_file', 0, array(), array(
    'test_form' => false,
    'mimes'     => array(
        'csv'   => 'text/csv',
    ),
) );

When I upload a CSV file to the form I get the following error message…

Sorry, this file type is not permitted for security reasons.

Can anyone spot what I am doing wrong? I had assumed I had allowed the CSV mime type in the above code.

3 s
3

There’s a bug in WordPress 4.7-4.7.3 related to validating MIME types, so the code provided by Dave Romsey won’t work.

There’s a plugin in the repo that will bypass MIME checks, but it disables the checks for all users and all extensions. I think a better way would be to add a new capability for administrators that will allow them to upload .csv extensions.

//* Register activation and deactivation hooks
register_activation_hook( __FILE__ , 'wpse_258192_activation' );
register_deactivation_hook( __FILE__ , 'wpse_258192_deactivation' );

//* Add upload_csv capability to administrator role
function wpse_258192_activation() {
  $admin = get_role( 'administrator' );
  $admin->add_cap( 'upload_csv' );
}

//* Remove upload_csv capability from administrator role
function wpse_258192_deactivation() {
  $admin = get_role( 'administrator' );
  $admin->remove_cap( 'upload_csv' );
}

//* Add filter to check filetype and extension
add_filter( 'wp_check_filetype_and_ext', 'wpse_258192_check_filetype_and_ext', 10, 4 );

//* If the current user can upload_csv and the file extension is csv, override arguments - edit - "$pathinfo" changed to "pathinfo"
function wpse_258192_check_filetype_and_ext( $args, $file, $filename, $mimes ) {
  if( current_user_can( 'upload_csv' ) && 'csv' === pathinfo( $filename )[ 'extension' ] ){
    $args = array(
      'ext'             => 'csv',
      'type'            => 'text/csv',
      'proper_filename' => $filename,
    );
  }
  return $args;
}

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *