Hongmu Notes
Home Language Notes PHP: Remote download of a ZIP file, extract it, and overwrite it into a specified directory.
Language Notes PHP

PHP: Remote download of a ZIP file, extract it, and overwrite it into a specified directory.

PHP: Remote download of a ZIP file, extract it, and overwrite it into a specified directory.

This feature is commonly used for updating applications – I suppose you already know how to use it!

very functional!

PHP implementation code:

// 远程 zip 文件的 URL
$zipUrl = 'https://example.com/install.zip';

// 目标文件路径
$targetPath = '/path/to/install';

// 下载 zip 文件
$zipData = file_get_contents($zipUrl);

if ($zipData === false) {
  die('Failed to download ZIP file.');
}

// 清空目录
function emptyDir($dir) {
  $files = array_diff(scandir($dir), array('.', '..'));
  foreach ($files as $file) {
    if (is_dir("$dir/$file")) {
      emptyDir("$dir/$file");
      rmdir("$dir/$file");
    } else {
      unlink("$dir/$file");
    }
  }
}

emptyDir($targetPath);

// 解压缩文件
$zip = new ZipArchive;
if ($zip->open('install.zip') === true) {
  $zip->extractTo($targetPath);
  $zip->close();
  echo 'Success!';
} else {
  echo 'Failed to unzip file.';
}

Wrap into a function:

function downloadAndExtract($installDir, $remoteZipUrl) {
    // 删除指定目录及其下所有文件
    if (is_dir($installDir)) {
        $files = glob($installDir . '/*');
        foreach ($files as $file) {
            if (is_file($file)) {
                unlink($file);
            } elseif (is_dir($file)) {
                $innerFiles = glob($file . '/*');
                foreach ($innerFiles as $innerFile) {
                    if (is_file($innerFile)) {
                        unlink($innerFile);
                    }
                }
                rmdir($file);
            }
        }
        rmdir($installDir);
    }

    // 创建指定目录
    if (!mkdir($installDir, 0777, true)) {
        throw new Exception('Failed to create install directory.');
    }

    // 下载远程 Zip 文件并保存到本地
    $tempZip = tempnam(sys_get_temp_dir(), 'download_');
    $fp = fopen($tempZip, 'w');
    $ch = curl_init($remoteZipUrl);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    $success = curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    if (!$success) {
        throw new Exception('Failed to download the remote ZIP file.');
    }

    // 解压缩文件到指定目录
    $zip = new ZipArchive();
    if ($zip->open($tempZip) === TRUE) {
        $zip->extractTo($installDir);
        $zip->close();
    } else {
        throw new Exception('Failed to extract the ZIP file.');
    }

    // 删除临时文件
    unlink($tempZip);
}

This function uses PHP's built-in ZipArchive class to decompress ZIP files, and employs the glob() function to list all files within the `install` directory and delete them. Note that the Zip extension must be enabled in PHP; otherwise, the ZipArchive class will not function.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

(Adaptive mobile version) HTML5 PBootCMS template for heavy-industry equipment manufacturing enterprise websites; Download source code for large-scale mining and heavy-industry equipment websites – 0198

(Adaptive mobile version) HTML5 PBootCMS template for heavy-industry equipment manufacturing enterprise websites; Download source code for large-scale mining and heavy-industry equipment websites – 0198 Practical Collection pbootcms Template

An adaptive HTML5 corporate website template for heavy-industry equipment and manufacturing businesses, built with PbootCMS. Its robust and professional design is ideal for showcasing large-scale mining equipment, heavy machinery, and manufacturing capabilities. This template enables heavy-industry equipment companies to showcase their products online and expand their presence in both domestic and international industrial markets. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www...
👁 37
Environmental Protection – New Materials & New Energy Recycling Website Template 0024

Environmental Protection – New Materials & New Energy Recycling Website Template 0024 Practical Collection Yiyou template

This EyouCMS template is ideal for enterprises specializing in eco-friendly new materials or new energy recycling. Its green technology design style is perfect for showcasing innovative environmental materials, energy recovery technologies, and related products. It helps environmental protection companies build a strong green brand image online and attract potential partners. Template Demo | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 33
Responsive Medical Device Company Website Template 1066

Responsive Medical Device Company Website Template 1066 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for medical device companies, featuring a professional and clean design that effectively showcases medical device products, technical specifications, clinical applications, and corporate branding. It enables medical device companies to present their products online and attract potential clients, including hospitals and distributors. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | Eyou...
👁 45
(Adaptive mobile version) HTML5 – Simplified/Traditional Chinese fonts; Green wide-screen logistics and transportation website using PBootCMS template; Responsive, professional express delivery and freight transport website source code download – 0199

(Adaptive mobile version) HTML5 – Simplified/Traditional Chinese fonts; Green wide-screen logistics and transportation website using PBootCMS template; Responsive, professional express delivery and freight transport website source code download – 0199 Practical Collection pbootcms Template

This is an adaptive HTML5 PbootCMS responsive website template designed for mobile devices, featuring both Simplified and Traditional Chinese fonts and is ideal for express delivery, logistics, and freight companies to showcase their service networks. It helps logistics enterprises enhance their brand promotion across the Taiwan Strait market. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5...
👁 65
Centrifugal Fan Mechanical Manufacturing Website Template 0025

Centrifugal Fan Mechanical Manufacturing Website Template 0025 Practical Collection Yiyou template

An EyouCMS website template designed for centrifugal fan manufacturing enterprises. Its professional industrial design style effectively showcases centrifugal fan products, technical specifications, and industrial applications. This template helps fan equipment manufacturers demonstrate their product capabilities online and attract industrial customers. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS...
👁 45
Responsive Digital Product Company Website Template (Bilingual) 1067

Responsive Digital Product Company Website Template (Bilingual) 1067 Practical Collection Yiyou template

An eyouCMS responsive bilingual website template designed for digital product manufacturers. Its modern, international design style effectively showcases digital products, technical specifications, export advantages, and global market presence. The multi-language support enables digital brands to present their brand image effectively in international markets. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eyouCMS | eyouCMS...
👁 62