Click here to Skip to main content
15,299,443 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am tring to create a zip file and download .I have been working on for hours but I couldnt make it to run.It creates the zip file but download the orginial file

What I have tried:

<table class="table table-bordered">
<tr>
<td>Name</td>
<td></td>
</tr>
<tr>


<?php

while ($row = mysqli_fetch_array($data)) {
    ?>
<tr>
<td><?php echo $row['filename']; ?></td>
<td><a href="ajax.php?id=<?php echo $row['id']; ?>">Download</a></td>

</tr>
	<?php
}

?>


</tr>
</table>



------------------------------------
<?php

$id = $_GET['id'];

$con = mysqli_connect('localhost', 'root', '', 'test');
$data = mysqli_query($con, "select * from files where id={$id}");
$name = '';
foreach ($data as $d) {
    $name = $d['filename'];
}

$zip = new ZipArchive();
$zip->open('zipped.zip', ZipArchive::CREATE);
$zip->addFile($name);
$zip->close();
if (file_exists($name)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename='.$name);
    header('Content-Length: '.filesize($name));
    //ob_clean();
    //flush();
    readfile($name);
}
Posted
Updated 16-Nov-18 7:54am
v3

1 solution

Because that's exactly what you're telling it to do!

$name contains the name of the original file:
$name = $d['filename'];

You create a ZipArchive, and add that file to it:
$zip = new ZipArchive();
$zip->open('zipped.zip', ZipArchive::CREATE);
$zip->addFile($name);
$zip->close();

You then transmit the original file to the user:
if (file_exists($name)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename='.$name);
    header('Content-Length: '.filesize($name));
    //ob_clean();
    //flush();
    readfile($name);
}

You need to transmit the zip file to the user instead:
if (file_exists('zipped.zip')) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename=zipped.zip');
    header('Content-Length: '.filesize('zipped.zip'));
    readfile('zipped.zip');
}
   
Comments
Member 3722539 17-Nov-18 4:13am
   
thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900