1

I am using phpdocx to create a word document. It is a valid word document when I look at it on the server. However, when I try to download it, it says that the file cannot be opened because there are problems with the file. Word is able to recover the document, but it clients will complain about an invalid word document. Here is the code I use to download the file:

function readfile_chunked_remote($filename, $seek = 0, $retbytes = true, $timeout = 3) {
    set_time_limit(0); 
    $defaultchunksize = 1024*1024; 
    $chunksize = $defaultchunksize; 
    $buffer = ''; 
    $cnt = 0; 
    $remotereadfile = false; 


if (preg_match('/[a-zA-Z]+:\/\//', $filename)) 
$remotereadfile = true; 

$handle = @fopen($filename, 'rb'); 

if ($handle === false) { 
return false; 
} 

stream_set_timeout($handle, $timeout); 

if ($seek != 0 && !$remotereadfile) 
fseek($handle, $seek); 

while (!feof($handle)) { 

if ($remotereadfile && $seek != 0 && $cnt+$chunksize > $seek) 
    $chunksize = $seek-$cnt; 
else 
    $chunksize = $defaultchunksize; 

$buffer = @fread($handle, $chunksize); 

if ($retbytes || ($remotereadfile && $seek != 0)) { 
    $cnt += strlen($buffer); 
} 

if (!$remotereadfile || ($remotereadfile && $cnt > $seek)) 
    echo $buffer; 

ob_flush(); 
flush(); 
} 

$info = stream_get_meta_data($handle); 

$status = fclose($handle); 

if ($info['timed_out']) 
return false; 

if ($retbytes && $status) { 
return $cnt; 
} 

return $status; 

}

Thanks!

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
ELK
  • 11
  • 2
  • why don't you just use `file_get_contents` or something else that is simpler to return file? – E_p Nov 27 '12 at 21:50
  • It has the same error. The Word document downloads, but it has to be repaired before it can be viewed. – ELK Nov 27 '12 at 22:10
  • Could the problem be in the headers I set? `header('Content-Description: File Transfer'); header('Content-Type: application/vnd.ms-word'); header('Content-Disposition: filename="'. $_GET['syllabusId'] . '.docx'); header('Content-Transfer-Encoding: binary'); ('Expires: 0'); ('Pragma: public'); ('Content-Length:'.filesize($fileLoc));` – ELK Nov 27 '12 at 22:13
  • Do not think so if error is on file opening. Did you try to create an empty file and than open it. Is it possible that some of the elements you create invalid for some reason? – E_p Nov 27 '12 at 22:15
  • No, I do not create and open an empty file. I am not aware of any elements that are invalid. – ELK Nov 27 '12 at 22:20
  • I managed to find a solution to my problem on stackoverflow: [http://stackoverflow.com/questions/10145067/why-my-downloaded-file-is-alwayes-damaged-or-corrupted][1]. [1]: http://stackoverflow.com/questions/10145067/why-my-downloaded-file-is-alwayes-damaged-or-corrupted – ELK Nov 28 '12 at 17:34

0 Answers0