函数文档

unzip_file()

💡 云策文档标注

概述

unzip_file() 是 WordPress 核心函数,用于通过 WordPress 文件系统抽象层解压 ZIP 文件到指定位置。它依赖于 WP_Filesystem 的初始化,并自动处理内存限制和目录创建。

关键要点

  • 函数通过 WordPress 文件系统抽象层操作,需确保 WP_Filesystem() 已调用并设置。
  • 参数包括 $file(ZIP 文件完整路径)和 $to(解压目标路径),均为必需字符串。
  • 返回值为 true(成功)或 WP_Error(失败),便于错误处理。
  • 自动尝试将 PHP 内存限制提升至 256M,以支持大文件解压。
  • 优先使用 ZipArchive 类解压,若不可用或出错则回退到 PclZip 库。
  • 过滤钩子 apply_filters('unzip_file_use_ziparchive', bool $ziparchive) 可控制是否使用 ZipArchive。
  • 解压时会跳过根级的 __MACOSX 目录,并自动创建所需父目录。

代码示例

// 基本示例:解压 WordPress 上传目录中的 ZIP 文件到同一位置
$file = WP_CONTENT_DIR . '/uploads/archive.zip';
$to = WP_CONTENT_DIR . '/uploads/';
$result = unzip_file($file, $to);
if (is_wp_error($result)) {
    echo '解压失败: ' . $result->get_error_message();
} else {
    echo '解压成功';
}

注意事项

  • 调用前必须确保 WP_Filesystem() 已正确初始化,否则可能返回 WP_Error。
  • 函数内部处理内存提升,但实际内存需求不应远大于归档文件本身。
  • 解压过程可能受服务器配置和文件大小影响,建议在开发环境中测试。

📄 原文内容

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

Description

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

$filestringrequired
Full path and filename of ZIP archive.
$tostringrequired
Full path on the filesystem to extract archive to.

Return

true|WP_Error True on success, WP_Error on failure.

Source

function unzip_file( $file, $to ) {
	global $wp_filesystem;

	if ( ! $wp_filesystem || ! is_object( $wp_filesystem ) ) {
		return new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
	}

	// Unzip can use a lot of memory, but not this much hopefully.
	wp_raise_memory_limit( 'admin' );

	$needed_dirs = array();
	$to          = trailingslashit( $to );

	// Determine any parent directories needed (of the upgrade directory).
	if ( ! $wp_filesystem->is_dir( $to ) ) { // Only do parents if no children exist.
		$path = preg_split( '![/\]!', untrailingslashit( $to ) );
		for ( $i = count( $path ); $i >= 0; $i-- ) {
			if ( empty( $path[ $i ] ) ) {
				continue;
			}

			$dir = implode( '/', array_slice( $path, 0, $i + 1 ) );
			if ( preg_match( '!^[a-z]:$!i', $dir ) ) { // Skip it if it looks like a Windows Drive letter.
				continue;
			}

			if ( ! $wp_filesystem->is_dir( $dir ) ) {
				$needed_dirs[] = $dir;
			} else {
				break; // A folder exists, therefore we don't need to check the levels below this.
			}
		}
	}

	/**
	 * Filters whether to use ZipArchive to unzip archives.
	 *
	 * @since 3.0.0
	 *
	 * @param bool $ziparchive Whether to use ZipArchive. Default true.
	 */
	if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
		$result = _unzip_file_ziparchive( $file, $to, $needed_dirs );
		if ( true === $result ) {
			return $result;
		} elseif ( is_wp_error( $result ) ) {
			if ( 'incompatible_archive' !== $result->get_error_code() ) {
				return $result;
			}
		}
	}
	// Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
	return _unzip_file_pclzip( $file, $to, $needed_dirs );
}

Hooks

apply_filters( ‘unzip_file_use_ziparchive’, bool $ziparchive )

Filters whether to use ZipArchive to unzip archives.

Changelog

Version Description
2.5.0 Introduced.

User Contributed Notes