unzip_file

Unzips a specified ZIP file to a location on the Filesystem via the WordPress Filesystem Abstraction.

Description

unzip_file( (string) $file, (string) $to ); 

Assumes that WP_Filesystem() has already been called and set up. Does not extract a root-level __MACOSX directory, if present.

Attempts to increase the PHP Memory limit to 256M before uncompressing, However, The most memory required shouldn't be much larger than the Archive itself.

Parameters (2)

0. $file (string)
Full path and filename of zip archive
1. $to (string)
Full path on the filesystem to extract archive to

Usage

  1. if ( !function_exists( 'unzip_file' ) ) { 
  2. require_once ABSPATH . '/wp-admin/includes/file.php'; 
  3.  
  4. // Full path and filename of zip archive 
  5. $file = ''; 
  6.  
  7. // Full path on the filesystem to extract archive to 
  8. $to = ''; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = unzip_file($file, $to); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-admin/includes/file.php  
  1. function unzip_file($file, $to) { 
  2. global $wp_filesystem; 
  3.  
  4. if ( ! $wp_filesystem || !is_object($wp_filesystem) ) 
  5. return new WP_Error('fs_unavailable', __('Could not access filesystem.')); 
  6.  
  7. // Unzip can use a lot of memory, but not this much hopefully. 
  8. wp_raise_memory_limit( 'admin' ); 
  9.  
  10. $needed_dirs = array(); 
  11. $to = trailingslashit($to); 
  12.  
  13. // Determine any parent dir's needed (of the upgrade directory) 
  14. if ( ! $wp_filesystem->is_dir($to) ) { //Only do parents if no children exist 
  15. $path = preg_split('![/\\\]!', untrailingslashit($to)); 
  16. for ( $i = count($path); $i >= 0; $i-- ) { 
  17. if ( empty($path[$i]) ) 
  18. continue; 
  19.  
  20. $dir = implode('/', array_slice($path, 0, $i+1) ); 
  21. if ( preg_match('!^[a-z]:$!i', $dir) ) // Skip it if it looks like a Windows Drive letter. 
  22. continue; 
  23.  
  24. if ( ! $wp_filesystem->is_dir($dir) ) 
  25. $needed_dirs[] = $dir; 
  26. else 
  27. break; // A folder exists, therefor, we dont need the check the levels below this 
  28.  
  29. /** 
  30. * Filters whether to use ZipArchive to unzip archives. 
  31. * @since 3.0.0 
  32. * @param bool $ziparchive Whether to use ZipArchive. Default true. 
  33. */ 
  34. if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) { 
  35. $result = _unzip_file_ziparchive($file, $to, $needed_dirs); 
  36. if ( true === $result ) { 
  37. return $result; 
  38. } elseif ( is_wp_error($result) ) { 
  39. if ( 'incompatible_archive' != $result->get_error_code() ) 
  40. return $result; 
  41. // Fall through to PclZip if ZipArchive is not available, or encountered anerroropening the file. 
  42. return _unzip_file_pclzip($file, $to, $needed_dirs);