如何限制上传的文件类型?

时间:2016-05-27 作者:User014019

我有一个自定义的网页模板与表单,任何网站的访问者都可以上传文件。现在,我想限制将上载的文件类型(仅限于docx、doc和pdf),并将文件大小限制为2MB。

如何做到这一点?我已经有了一个用户允许上传的函数,但我不知道如何限制允许上传的文件类型。请帮帮我。

我试图改变

\'post_mime_type\' => $file_return[\'type\']

进入这个

\'post_mime_type\' => \'application/msword,vnd.openxmlformats-officedocument.wordprocessingml.document,pdf\'

但它仍然不起作用。

自定义页面模板中的PHP

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。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;
}

3 个回复
SO网友:N00b

这是一个完整的工作示例,包含文件类型和大小限制以及所有错误处理。

每一步都有注释。如果你还有任何问题,请告诉我。

您可以从中找到所有mime类型here.allowed 也在WP中


// 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;
    }
}

SO网友:iyass.si

只需添加一条if语句,如:

    if ( $file["type"] != "application/pdf" ){
        exit;
    }
您可以在$\\u会话中添加消息,并重定向url以向用户显示错误

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

如果要使用$mimes,请以其他方式:

function your_mimes($mimes) {
  $mimes = array(\'pdf\' => \'application/pdf\');
  return $mimes;
}
您可以看到所有类型的列表:here然后在上载方法添加之前和之后:

add_filter(\'upload_mimes\',\'your_mimes\');
以及:

remove_filter(\'upload_mimes\',\'your_mimes\');
若你们并没有删除它,那个么它将在执行后应用于站点中的所有上传
希望对您有所帮助

SO网友:vee

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.\');
}
参考号:https://rundiz.com/?p=448

在里面mimes 数组键,可以使用多个文件扩展名,但必须能够在正则表达式中使用
根据我的示例:jpg|jpeg|jpe 表示文件扩展名可以是| 符号表示OR 数组值为mime类型。