How to limit file type to be upload?

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

Leave a Comment