unzip_file

函式
unzip_file ( $file, $to )
引數
  • (string) $file Full path and filename of ZIP archive.
    Required:
  • (string) $to Full path on the filesystem to extract archive to.
    Required:
返回值
  • (true|WP_Error) True on success, WP_Error on failure.
定義位置
相關方法
_unzip_file_pclzip_unzip_file_ziparchivedid_filterlist_filescurrent_filter
引入
2.5.0
棄用
-

unzip_file。解壓一個壓縮檔案: 該函式將一個壓縮檔案解壓到指定的目錄中,如果所有必要的目錄不存在,則建立這些目錄。

通過WordPress檔案系統抽象,將指定的ZIP檔案解壓到檔案系統中的某個位置。

假設WP_Filesystem()已經被呼叫和設定了。如果存在根級的__MACOSX目錄,則不提取。

在解壓縮之前,試圖將PHP的記憶體限制增加到256M。然而,最需要的記憶體不應該比檔案本身大很多。

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 );
}

常見問題

FAQs
檢視更多 >