0

I am trying to use the $wp_filesystem of WordPress to unzip a file located inside the wp-content/plugins and place it at the same location. However whatever I try the WordPress method unzip_file() always returns true as if it worked (but no file appeared on the server).

This is the code I have for unzipping the file:

WP_Filesystem();
$zip_from = get_home_path().'wp-content/plugins/'.$filename;
$zip_to = str_replace(ABSPATH, $wp_filesystem->abspath(), get_home_path().'wp-content/plugins/');
if(!unzip_file($zip_from,$zip_to))
{
    return new \WP_Error('writing_error', 'Couldn\'t extract the plugin\'s ZIP file.');
}
else exit("worked");

So then I dived into the unzip_file() method located inside WordPress' file.php file and found out that the script stops at the following position:

// Create those directories if need be:
foreach ( $needed_dirs as $_dir )
{
    // Only check to see if the Dir exists upon creation failure. Less I/O this way.
    if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) {
        // THIS IS WHERE THE SCRIPT STOPS       
        return new WP_Error( 'mkdir_failed_ziparchive', __( 'Could not create directory.' ), substr( $_dir, strlen( $to ) ) );
    }
}

When I checked var_dump($_dir) it returned /www, so $wp_filesystem->is_dir('/www') returned false. What could be the reason for this behaviour, the path seems right and it is a full path as stated in the documentation.

PS: Even the very basic example stated on the official documentation of unzip_file() (https://codex.wordpress.org/Function_Reference/unzip_file#Example) does not work (I get a success message, but no file is created).

1 Answer 1

0

In PHP, in too many contexts, false and true are more of a state of mind than actual values and not false is not the same as true If you want to check that something is a boolean true, then just check if it is === true.

In your case the function returns a WP_Error object which is not a boolean value at all and it probably includes the reason for the failure.

As for the actual reason for failure, it means you do not have permissions to write to the location you want to write to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.