我有这个脚本从数据库下载所有文件作为zip,但它只获得保存在数据库中的第一个文件 - 其他文件没有显示。
下面是我在数据库中的文件列表,我想在zip中包含这些文件:
lginin
logersutil.php
lgininh.js
Readme.md
我的代码:
<?php
if(isset($_POST['download'])){
try{
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$post_stmt = $db_conn->prepare("SELECT * FROM jailorgchild WHERE jailchildbasname = :BasNameJa");
$post_stmt->bindParam(':BasNameJa', basename(dirname(__FILE__)));
$post_stmt->execute();
while ($rowss = $post_stmt->fetch(PDO::FETCH_ASSOC)){
$files = array(''.$rowss["jailchillink"].'','codejail.cj');
# create new zip opbject
$zip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
# loop through each file
foreach($files as $file){
# download file
$download_file = file_get_contents($file);
#add it to the zip
$zip->addFromString(basename($file),$download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename='.basename(dirname(__FILE__)).'.zip');
header('Content-type: application/zip');
readfile($tmp_file);
} }catch (PDOException $e){ echo 'Connection failed: ' . $e->getMessage();}
}
?>
答案 0 :(得分:0)
在您当前的代码中,您基本上会创建一个新的zip文件并为每一行返回它。由于客户端只能读取1个响应,因此它们显然不会超过1行。
所以你需要做的是确保在发送之前将所有文件添加到zip 。像这样:
<?php
if(isset($_POST['download'])){
try{
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$post_stmt = $db_conn->prepare("SELECT * FROM jailorgchild WHERE jailchildbasname = :BasNameJa");
$post_stmt->bindParam(':BasNameJa', basename(dirname(__FILE__)));
$post_stmt->execute();
// here we create a temporary array to hold all the filenames
// and fill it with the file you always want to have inserted
$files = array('codejail.cj');
while ($rowss = $post_stmt->fetch(PDO::FETCH_ASSOC)){
// now fill the array with your files
$files[] = $rowss['jailchillink'];
}
// and now we finally start processing them all, after having finished reading from the DB
# create new zip opbject
$zip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
# loop through each file
foreach($files as $file){
# download file
$download_file = file_get_contents($file);
#add it to the zip
$zip->addFromString(basename($file),$download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename='.basename(dirname(__FILE__)).'.zip');
header('Content-type: application/zip');
readfile($tmp_file);
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
} ?&GT;