Unzip_file causing Media file upload error

When I attempt to use the unzip_file function below in my functions.php:

require_once(ABSPATH . 'wp-admin/includes/file.php');
WP_Filesystem();
$destination = wp_upload_dir();
$destination_path = $destination['path'];
$unzipfile = unzip_file( $destination_path.'/filename.zip', $destination_path);

if ( is_wp_error( $unzipfile ) ) {
    echo 'There was an error unzipping the file.'; 
} else {
    echo 'Successfully unzipped the file!';       
}

I get the following error when trying to upload any files into the Media library in Media > Add New:

An error occurred in the upload. Please try again later.

I am using Twenty Nineteen theme with no plugins activated. I don't get the error when I remove the function.

Any ideas?

Topic wp-filesystem functions php Wordpress

Category Web


I know this might be a little old, but after you get_attached_file, you can check the path for the extension (https://www.php.net/manual/en/function.pathinfo.php):

<?php

$file_path = get_attached_file( $post_ID );
$path_parts = pathinfo($file_path);

// do nothing if not zip
if ( path_parts['extension'] !== 'zip' ) {
   return;
}
     
require_once(ABSPATH . 'wp-admin/includes/file.php');
WP_Filesystem();
$destination = wp_upload_dir();
$destination_path = $destination['path'];
$unzipfile = unzip_file($file_path, $destination_path); 

I got it to work without errors by using it inside add_attachment hook below, but now the problem is it runs on every media upload.

function unzip_icon_fonts( $post_ID ){
    $file_path = get_attached_file( $post_ID );
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    WP_Filesystem();
    $destination = wp_upload_dir();
    $destination_path = $destination['path'];
    $unzipfile = unzip_file($file_path, $destination_path); 
}
add_action( 'add_attachment', 'unzip_icon_fonts' );

I tried restricting it to a specific Customizer file upload below, but then it doesn't work at all.

function unzip_icon_fonts( $post_ID ){
    // If attachment ID equals Customizer file upload ID added with WP_Customize_Media_Control
    if ( $post_ID == get_theme_mod('icon_fonts', '') ) {
        $file_path = get_attached_file( $post_ID );
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        WP_Filesystem();
        $destination = wp_upload_dir();
        $destination_path = $destination['path'];
        $unzipfile = unzip_file($file_path, $destination_path); 
    }
}
add_action( 'add_attachment', 'unzip_icon_fonts' );

Am I missing something?

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.