问题是当文件夹中有很多文件时,下面的脚本正在下载一个0字节的zip文件。
我也用if(file_exists="/folder/path/file.txt)子句测试过,脚本似乎可以找到文件。我做错了什么?
<?php
// Define the folder to be zipped
$folder_path = '/CA11.2.4/logs/';
// Define the name of the zipped file with a timestamp
$zip_file_name = 'logs_' . date('Ymd_His') . '.zip';
// Create a new ZipArchive instance
$zip = new ZipArchive();
// Open the zip file for writing
if ($zip->open($zip_file_name, ZipArchive::CREATE) !== TRUE) {
die ('Could not create zip archive');
}
// Add the files from the folder to the zip file
$dir = opendir($folder_path);
while ($file = readdir($dir)) {
if (is_file($folder_path . $file)) {
$zip->addFile($folder_path . $file, $file);
}
}
// Close the directory handle
closedir($dir);
// Close the zip file
$zip->close();
// Set headers to force download the zip file
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zip_file_name . '"');
header('Content-Length: ' . filesize($zip_file_name));
// Send the zip file to the client for download
readfile($zip_file_name);
// Delete the zip file from the server
//unlink($zip_file_name);
// Redirect back to the referring page
//header('Location: ' . $_SERVER['HTTP_REFERER']);
?>
我最初怀疑可能是它没有检测到路径,所以我添加了这个片段,并注解掉其他代码来验证,它工作了。
<?php
$path = '/path/to/folder/file.txt';
if (file_exists($path)) {
echo 'Path exists on server';
} else {
echo 'Path does not exist on server';
}
1条答案
按热度按时间wn9m85ua1#
在我看来,这个问题很可能是路径问题,而不是Zip问题。在PHP中,根据我的经验,最好使用绝对路径,不要假设2个单独的文件知道/理解它们位于与X相关的位置。
然后下载: