title: PHP - simple download script
body: <p>I'm making a simple download script, where my users can download their own images etc.</p>
  
  <p>But I'm having some weird problem.</p>
  
  <p>When I've downloaded the file, it's having the contents from my index.php file no matter what filetype I've downloaded.. My code is like so:</p>
  
  <pre><code>$fullPath = $r['snptFilepath'] . $r['snptFilename'];
  
  if (file_exists($fullPath)) {
  
      #echo $fullPath;
  
      // setting headers
      header('Content-Description: File Transfer');
      header('Cache-Control: public'); # needed for IE
      header('Content-Type: '.$r['snptFiletype'].'');
      header('Content-Disposition: attachment; filename='. $filename . '.' . $r['snptExtension']);
      header('Content-Length: '.$r['snptSize'].'');
      readfile($fullPath)or die('error!');
  } else {
      die('File does not exist');
  }
  </code></pre>
  
  <p>$r is the result from my database, where I've stored size, type, path etc. when the file is uploaded.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>When I'm uploading and downloading *.pdf files it's working with success. But when I'm trying to download *.zip and text/rtf, text/plain it's acting weird.</p>
  
  <p>By weird I mean: It downloads the full index.php file, with the downloaded file contents inside of it.</p>
  
  <p><strong>ANSWER</strong></p>
  
  <p>I copied this from <a href="http://php.net/manual/en/function.readfile.php" rel="noreferrer">http://php.net/manual/en/function.readfile.php</a> and it's working now. It seems that : ob_clean(); did the trick! Thanks for the help everyone.</p>
  
  <pre><code>#setting headers
      header('Content-Description: File Transfer');
      header('Content-Type: '.$type);
      header('Content-Disposition: attachment; filename='.basename($file));
      header('Content-Transfer-Encoding: binary');
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize($file));
      ob_clean();
      flush();
      readfile($file);
      exit;
  </code></pre>