PHP corrupted file

129 views Asked by At

This is the page where I click on the download button.

This is the things I found online but it did not work

why my downloaded file is alwayes damaged or corrupted?

Force Downloading a PDF file, corrupt file

$query = "SELECT id, name FROM docu";
$result = mysqli_query($con,$query) or die('Error, query failed');

if(mysqli_num_rows($result)==0){
    echo "Database is empty <br>";
}
else{
    while ( (list($id, $name) = mysqli_fetch_array($result, MYSQLI_BOTH))){
?>
<p><a href="download.php?id=<?= $id ?>">Name : <?= $name ?></a></p>

This is the download code. When I download the file, it say it is corrupted.

if(isset($_GET['id'])){
 $id    = $_GET['id'];

 $con = mysqli_connect("localhost:3306", "waduser", "waduser", "fyp");
if(!$con) {
  die("cannot connect: " . mysqli_error());
 }
 mysqli_select_db($con,"fyp");

 $query = "SELECT * FROM docu where id ='" .$id ."'";
 $result = mysqli_query($con,$query) or die('Error, query failed');
 if($row =  $result ->  fetch_array(MYSQLI_ASSOC))
 {
    $name = $row['name'];
    $type = $row['type'];
    $content = $row['content']; //content of file
    $size = $row['size']; //file size
    header('Content-Type:"' . $type . '"');
    header('Content-length:' . $size  .'');
    header('Content-Disposition: attachment; filename="' .$name. '"');

  } 
 }
?>
1

There are 1 answers

3
RiggsFolly On

I think what Jim is trying to say is that you have sent all the headers but you have not actually sent the file itself.

So try

$name = $row['name'];
$type = $row['type'];
$content = $row['content']; //content of file
$size = $row['size']; //file size
header('Content-Type:"' . $type . '"');
header('Content-length:' . $size  .'');
header('Content-Disposition: attachment; filename="' .$name. '"');
echo $content;

Also I think its safer to remove the spaces around your short_tag usage at least in the href property.

<p><a href="download.php?id=<?=$id?>">Name : <?= $name ?></a></p>