Home > Backend Development > PHP Tutorial > How to decompress zip file in PHP? (code example)

How to decompress zip file in PHP? (code example)

青灯夜游
Release: 2023-04-09 09:36:02
forward
5450 people have browsed it

How to decompress zip file in PHP? (code example)

PHP decompresses the zip file

1. Use the PHP execution file to decompress the zip file. As a prerequisite, you must make sure that the server has zip enabled. Expansion

2. The encapsulation method is as follows:

Example code

<?php
/**
 * 压缩文件
 * @param array $files 待压缩文件 array(&#39;d:/test/1.txt&#39;,&#39;d:/test/2.jpg&#39;);【文件地址为绝对路径】
 * @param string $filePath 输出文件路径 【绝对文件地址】 如 d:/test/new.zip
 * @return string|bool
 */
function zip($files, $filePath) {
    //检查参数
    if (empty($files) || empty($filePath)) {
        return false;
    }

    //压缩文件
    $zip = new ZipArchive();
    $zip->open($filePath, ZipArchive::CREATE);
    foreach ($files as $key => $file) {
        //检查文件是否存在
        if (!file_exists($file)) {
            return false;
        }
        $zip->addFile($file, basename($file));
    }
    $zip->close();

    return true;
}

/**
 * zip解压方法
 * @param string $filePath 压缩包所在地址 【绝对文件地址】d:/test/123.zip
 * @param string $path 解压路径 【绝对文件目录路径】d:/test
 * @return bool
 */
function unzip($filePath, $path) {
    if (empty($path) || empty($filePath)) {
        return false;
    }

    $zip = new ZipArchive();

    if ($zip->open($filePath) === true) {
        $zip->extractTo($path);
        $zip->close();
        return true;
    } else {
        return false;
    }
}
?>
Copy after login

Related tutorial recommendations: "PHP Tutorial"

The above is the detailed content of How to decompress zip file in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template