這個功能常用於更新程序之類的,應該不用我說了!
非常實用!
PHP實現代碼:
// 遠程 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.';
}封裝成函數:
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);
}這個函數使用 PHP 內置的 ZipArchive 類來解壓縮 ZIP 文件,並使用 glob 函數來列出 install 目錄下的所有文件並刪除它們。注意需要開啓 PHP 的 Zip 擴展,否則 ZipArchive 類將無法使用。