title: How to fix PDF files corrupted when downloaded via PHP
body: <h1>The problem</h1>
  
  <p>I just rebuilt our website, in which we allow users to download .pdf and .mp3 files. I'm using a PHP script to handle the download process. The problem is that, with .pdf files, most of the times the downloads succeed. But certain times, I don't know why, the downloaded file is corrupted. Or, actually, Adobe Reader says "There was an error opening this document. The file is damaged and could not be repaired". If I open the same damaged file with another reader, it works fine.</p>
  
  <h1>What I already did</h1>
  
  <p>What I did is I opened both a "good" file and a "damaged" file with Notepad++. I found that the problem is that the damaged file, instead of ending with %%EOF, there's more stuff after %%EOF. It looks like if the beginning of the PDF file has been copied to the end of the file. 
  I also checked the file stored on the server, and it is good. 
  So, at this point, I think there's something wrong with the php script that handles the download. </p>
  
  <h1>Here's the code:</h1>
  
  <pre><code>    &lt;?php
  
      $file =$_GET['file']; 
      if(file_exists($file)) {
  
        $fileExtension = substr($file, -3);
        if($fileExtension === "pdf"){
          $filenameIndex = strpos($file, "pdf/") + 4;
          $filename = basename($file);
  
        }
        elseif ($fileExtension === "mp3") {
          $filenameIndex = strpos($file, "mp3/") + 4;
          $filename = basename($file);
        }
  
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.$filename.'"');
        header('Content-length: '. filesize($file));
        header('X-Pad: avoid browser bug');
        header('Cache-Control: no-cache');
        header('Content-Transfer-Encoding: chunked');
        readfile($file);
        print file_get_contents($file);
        exit;
      }
      ?&gt;
  </code></pre>
  
  <p>I use the same script to download both .pdf and .mp3 files. </p>
  
  <p>I'm NOT a php expert. And don't really understand how php handles downloads, so I would really appreciate if somebody could help me find the problem. Thank you very much in advance!</p>