php下实现文件下载实现代码

文章介绍了利用php来实现读取文件并且下载的代码,php要下载文件必须用到header函数,大家可参考一下,代码如下:

  1. <?php
  2. $file = 'monkey.gif';
  3. if (file_exists($file)) {
  4. header('Content-Description: File Transfer');
  5. header('Content-Type: application/octet-stream');
  6. header('Content-Disposition: attachment; filename='.basename($file));
  7. header('Content-Transfer-Encoding: binary');
  8. header('Expires: 0');
  9. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  10. header('Pragma: public');
  11. header('Content-Length: ' . filesize($file));
  12. ob_clean();
  13. flush();
  14. readfile($file);
  15. exit;
  16. }
  17. ?>

以上代码是下载代码,接下来贴一段在线预览pdf文件的代码:

  1. <?php
  2. public function fddAction()
  3. {
  4. // get attachment location
  5. $attachment_location = $_SERVER["DOCUMENT_ROOT"] . "/pdf/fdd/sample.pdf";
  6. if (file_exists($attachment_location)) {
  7. // attachment exists
  8. // send open pdf dialog to user
  9. header('Cache-Control: public'); // needed for i.e.
  10. header('Content-Type: application/pdf');
  11. header('Content-Disposition: inline; filename="sample.pdf"');
  12. readfile($attachment_location);
  13. die(); // stop execution of further script because we are only outputting the pdf
  14. } else {
  15. die('Error: File not found.');
  16. }
  17. }
  18. ?>