Frankzcodz
Frankzcodz

Reputation: 29

PHP file download empty

Please help, this code downloads file but file is empty(0byte) but inside the folder its 1mb.

function dowloadbooks($id){
$allbooks ="SELECT * FROM books_table WHERE books_id = '$id' ";
$result=$this->conn->query($allbooks);
$row = array();

if($result->num_rows >0){ 

while($res = $result->fetch_assoc()){

$row = $res['book_upload'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' .$row.'');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($row));
readfile($row); 
} 
} 
return $row;
}

Upvotes: 0

Views: 310

Answers (1)

Ziarek
Ziarek

Reputation: 857

I suggest you break your problem into smaller chunks:

Your file does not exist most likely or you are using the wrong path relative to your script. When I modify your example to use an existing file and exclude DB functionality, the file downloads correctly with no errors:

dowloadbooks();
function dowloadbooks(){

    $row = 'c:/ExistingFile.png';

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' .$row.'');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($row));
readfile($row); 
return $row;
}

Let's try the same example with non existing file:

    //error_reporting(0);
dowloadbooks();
function dowloadbooks(){

    $row = 'c:/NonExistingFile.png';

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' .$row.'');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($row));
readfile($row); 
return $row;
}

I get two errors:

PHP Warning:  filesize(): stat failed for c:/NonExistingFile.png in test.php on line 13
PHP Warning:  readfile(c:/NonExistingFile.png): failed to open stream: No such file or directory in test.php on line 14

But when I disable the error reporting with error_reporting(0), suddenly the file is downloading with zero size!!!

Conclusion:

Try displaying the file path first or/and enable errors with error_reporting(-1) - you should see where the problem is.

Upvotes: 1

Related Questions