php強制檔案下載(避免檔案或圖片直接在瀏覽器中開啟)

來源:互聯網
上載者:User
  1. /**
  2. * FLEA_Helper_SendFile 類用於向瀏覽器傳送檔案
  3. *
  4. * 利用 FLEA_Helper_SendFile,應用程式可以將重要的檔案儲存在
  5. * 瀏覽器無法訪問的位置。然後通過程式將檔案內容發送給瀏覽器。
  6. * @site http://bbs.it-home.org
  7. */
  8. class FLEA_Helper_SendFile
  9. {
  10. /**
  11. * 向瀏覽器傳送檔案內容
  12. *
  13. * @param string $serverPath 檔案在伺服器上的路徑(絕對或者相對路徑)
  14. * @param string $filename 發送給瀏覽器的檔案名稱(儘可能不要使用中文)
  15. * @param string $mimeType 指示檔案類型
  16. */
  17. function sendFile($serverPath, $filename, $mimeType = 'application/octet-stream')
  18. {
  19. header("Content-Type: {$mimeType}");
  20. $filename = '"' . htmlspecialchars($filename) . '"';
  21. $filesize = filesize($serverPath);
  22. $charset = FLEA::getAppInf('responseCharset');//根據實際檔案編碼類別型,如utf-8,gbk
  23. header("Content-Disposition: attachment; filename={$filename}; charset={$charset}");
  24. header('Pragma: cache');
  25. header('Cache-Control: public, must-revalidate, max-age=0');
  26. header("Content-Length: {$filesize}");
  27. readfile($serverPath);
  28. exit;
  29. }
  30. }
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.