WordPress File Upload Process

This function has created for wordpress file uploading . You can easily upload your file with the help of this function.

function file_upload() {
    $upload = array(
        'name' => $_FILES['file']['name'],
        'type' => $_FILES['file']['type'],
        'tmp_name' => $_FILES['file']['tmp_name'],
        'error' => $_FILES['file']['error'],
        'size' => $_FILES['file']['size']
    );

    header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );

    $attach = handle_upload( $upload );

    if ( $attach['success'] ) {
        echo 'Successfully upload your file';
    } else {
        echo 'Fail to upload your file';
    }
}
function handle_upload( $upload_data ) {

    if ( ! function_exists( 'wp_handle_upload' ) ) {
       require_once( ABSPATH . 'wp-admin/includes/file.php' );
    }

    $uploaded_file = wp_handle_upload( $upload_data, array('test_form' => false) );

    if ( isset( $uploaded_file['file'] ) ) {
        $file_loc = $uploaded_file['file'];
        $file_name = basename( $upload_data['name'] );
        $file_type = wp_check_filetype( $file_name );
        $post_title = preg_replace( '/\.[^.]+$/', '', basename( $file_name ) );

        $attachment = array(
            'post_mime_type' => $file_type['type'],
            'post_title' => $post_title,
            'post_content' => '',
            'post_status' => 'inherit'
        );

        include( ABSPATH . 'wp-admin/includes/image.php' );
        $attach_id = wp_insert_attachment( $attachment, $file_loc );
        $attach_data = wp_generate_attachment_metadata( $attach_id, $file_loc );
        wp_update_attachment_metadata( $attach_id, $attach_data );
        return array('success' => true, 'attach_id' => $attach_id);
    }

    return array('success' => false, 'error' => $uploaded_file['error']);
}