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.