Hongmu Notes
Home Language Notes PHP script for remotely downloading a ZIP file, extracting it, and overwriting files into a specified directory; if the specified directory does not exist, it will be created; if the directory already exists, it will be emptied. The extracted ZIP file contains files with Chinese filenames.
Language Notes PHP

PHP script for remotely downloading a ZIP file, extracting it, and overwriting files into a specified directory; if the specified directory does not exist, it will be created; if the directory already exists, it will be emptied. The extracted ZIP file contains files with Chinese filenames.

PHP script for remotely downloading a ZIP file, extracting it, and overwriting files into a specified directory; if the specified directory does not exist, it will be created; if the directory already exists, it will be emptied. The extracted ZIP file contains files with Chinese filenames.

PHP script for remotely downloading a ZIP file, extracting it, and overwriting files into a specified directory; if the specified directory does not exist, it will be created; if the directory already exists, it will be emptied. The extracted ZIP file contains files with Chinese filenames!

I previously wrote an article titled"PHP: Remote download of a ZIP file, extract it, and overwrite it into a specified directory.You can refer to this, but after using it, I discovered a problem!

Code issue

That is, if the target directory does not exist, an error will be raised!

During the extraction process, an error occurred because the compressed file had a Chinese filename!

Of course, we could simply use the @ symbol to mask the first error directly, but after thinking about it, I still think it's better to make a change!

Problem Reflection

This time, let's refine it a bit; you can refer to this article:PHP-based archive extraction/compression tool; the archive contains a file with a Chinese name – why does an error occur after extraction?

Here, we'll combine these two examples and then optimize the code function!

code implementation

The following example code demonstrates how to remotely download a ZIP file, extract it, and overwrite files in a specified directory; if the specified directory does not exist, it will be created; if the directory already exists, it will be emptied. The extracted ZIP file contains files with Chinese filenames:

$remoteZipUrl = 'https://example.com/remote.zip'; // 远程zip文件的URL
$localDir = '/path/to/local/dir'; // 本地目录的路径

// 如果本地目录不存在,创建目录
if (!file_exists($localDir)) {
  mkdir($localDir, 0777, true);
}

// 如果本地目录存在,清空目录
if (file_exists($localDir) && is_dir($localDir)) {
  $files = glob($localDir . '/*'); // 获取目录下的所有文件
  foreach ($files as $file) {
    if (is_file($file)) {
      unlink($file); // 删除文件
    }
  }
}

// 下载zip文件到本地临时文件
$tempFile = tempnam(sys_get_temp_dir(), 'zip');
$fp = fopen($tempFile, 'w');
$ch = curl_init($remoteZipUrl);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
curl_close($ch);
fclose($fp);

// 解压zip文件到本地目录
$zip = new ZipArchive;
$res = $zip->open($tempFile);
if ($res === TRUE) {
  $zip->setOptions(array('default_charset' => 'UTF-8')); // 设置文件名编码方式为 UTF-8
  $zip->extractTo($localDir); // 解压缩到指定目录
  $zip->close();
  echo '解压缩完成';
} else {
  echo '解压缩失败';
}

// 删除本地临时文件
unlink($tempFile);

In this example, first check whether the local directory exists; if it does not exist, then use it. mkdir() The function creates a directory; if it already exists, it will be used. glob()unlink() Clear directory.

Then, use it. tempnam() The function creates a temporary file for downloading a remote ZIP file. Use. curl The function downloads a ZIP file from a remote URL to a local temporary file.

Next, use. ZipArchive Open a local temporary file and set the file name encoding to UTF-8. Finally, call the function. extractTo() Method: Decompress the ZIP file into the specified directory. Once decompression is complete, delete the local temporary files.

Note: Before using this code, ensure that it is already installed on the server. ZipArchive Extend and curl expand.

function encapsulation

 隐藏内容:登录后可查看
function downloadAndExtractZip($remoteZipUrl, $localDir) {
  // 如果本地目录不存在,创建目录
  if (!file_exists($localDir)) {
    mkdir($localDir, 0777, true);
  }

  // 如果本地目录存在,清空目录
  if (file_exists($localDir) && is_dir($localDir)) {
    $files = glob($localDir . '/*'); // 获取目录下的所有文件
    foreach ($files as $file) {
      if (is_file($file)) {
        unlink($file); // 删除文件
      }
    }
  }

  // 下载zip文件到本地临时文件
  $tempFile = tempnam(sys_get_temp_dir(), 'zip');
  $fp = fopen($tempFile, 'w');
  $ch = curl_init($remoteZipUrl);
  curl_setopt($ch, CURLOPT_FILE, $fp);
  curl_exec($ch);
  curl_close($ch);
  fclose($fp);

  // 解压zip文件到本地目录
  $zip = new ZipArchive;
  $res = $zip->open($tempFile);
  if ($res === TRUE) {
    $zip->setOptions(array('default_charset' => 'UTF-8')); // 设置文件名编码方式为 UTF-8
    $zip->extractTo($localDir); // 解压缩到指定目录
    $zip->close();
    unlink($tempFile); // 删除本地临时文件
    return true;
  } else {
    unlink($tempFile); // 删除本地临时文件
    return false;
  }
}

This function takes as parameters the URL of the remote ZIP file and the path to the local directory. It will check whether the local directory exists; if it does not, it will use the default path. mkdir() The function creates a directory; if it already exists, it will be used. glob()unlink() Clear directory.

Then, use it. tempnam() The function creates a temporary file for downloading a remote ZIP file. Use. curl The function downloads a ZIP file from a remote URL to a local temporary file.

Next, use. ZipArchive Open a local temporary file and set the file name encoding to UTF-8. Finally, call the function. extractTo() Method: Decompress the ZIP file into the specified directory. Once decompression is complete, delete the local temporary files.

If the decompression is successful, the function will return. trueOtherwise, return. false

Error:

An error occurred after running the function!!!

If you encounter any errors, please read these three articles of mine!!

Fatal error: Call to undefined method ZipArchive::setOptions() – Solution!

How to check if ZipArchive is installed in your PHP environment?

Fatal error: Call to undefined method ZipArchive::setOptions() in /www/wwwroot/test.4s5.cn/1.php on line 37

final project

If implementing the solution does not resolve the ZipArchive extension issue, then you may want to read this article!

PclZip serves as a replacement for ZipArchive, resolving PHP error issues!

Of course, if your server supports ZipArchive and the above function code is working correctly, you may skip this section.

 
微信赞赏

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) SEO-optimized Blog Website Template – 1088

(Adaptive Mobile Version) SEO-optimized Blog Website Template – 1088 Practical Collection pbootcms Template

A SEO-optimized PbootCMS website template compatible with both PC and WAP devices. Its clean and informative design makes it ideal for SEO bloggers to share optimization techniques, industry trends, and case studies. This template helps SEO professionals build their personal brand and knowledge influence online. Template Preview | Installation Instructions | Website Admin Panel: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 58
Responsive Furniture Customization Website Template 0920

Responsive Furniture Customization Website Template 0920 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the custom furniture industry, featuring a high-end, modern design style that effectively showcases custom furniture products, design projects, brand stories, and service processes. It helps custom furniture brands attract homeowners online and enhance their brand image. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 62
(PC+WAP) doors and windows customized pbootcms website template aluminum alloy doors and windows website source code download 0126

(PC+WAP) doors and windows customized pbootcms website template aluminum alloy doors and windows website source code download 0126 Practical Collection pbootcms Template

A PbootCMS website template about door and window customization and aluminum alloy doors and windows industry, supporting PC and WAP access. The design style is modern and simple, which can well display the door and window product series and installation cases. It is a good choice for door and window brands or aluminum alloy processing companies to build official brand websites and improve online customer acquisition capabilities. Template display Installation instructions Website backend:/admin.php Account: admin Password: admin Unzip...
👁 41
(Adaptive Mobile Version) Membrane Structure Manufacturer Website Template Download – 1089

(Adaptive Mobile Version) Membrane Structure Manufacturer Website Template Download – 1089 Practical Collection pbootcms Template

A PbootCMS website template designed for membrane structure manufacturers, compatible with both PC and WAP devices. Its modern and professional design is ideal for showcasing membrane structure products, project cases, and design expertise. This template helps membrane structure companies promote their brand online and attract architectural and commercial clients. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 50
Responsive Furniture Sales Website Template 0921

Responsive Furniture Sales Website Template 0921 Practical Collection Yiyou template

An EyouCMS responsive website template designed specifically for the furniture and home furnishings sales industry. Its modern and practical design is ideal for showcasing furniture products, furniture collections, home decor combinations, and brand stories. This template helps furniture brands showcase their products online and attract home consumers. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 48
(PC+WAP)陶粒批发企业网站 – pbootCMS template; Engineering and Construction Materials Website Source Code Download – 0127

(PC+WAP)陶粒批发企业网站 – pbootCMS template; Engineering and Construction Materials Website Source Code Download – 0127 Practical Collection pbootcms Template

This PbootCMS template is designed for the expanded clay aggregate wholesale and construction materials industries, supporting both PC and mobile devices. Its pragmatic and professional design effectively showcases the applications of expanded clay aggregate products in the construction sector. It enables building material suppliers to display product specifications and project cases online, helping them expand their customer base within the construction industry. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4...
👁 50