PHP读取服务器端文件提供弹出下载窗口

流水孟春 2011-09-19 23:48:38 累计浏览 3,809 次

有些文件需要经过身份验证以后才能下载,我们不容用户知道下载的地址,甚至文件不存放在web文件夹下,感觉是不是做起来比较难呢?用PHP几行就可以了。这是在PHP官方手册提供的例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
}
?>

同分类推荐文章

  1. NGINX 1.31.7: Native GeoIP2 support, HTTP/2 priorities, and QUIC improvements (2026-11-13 23:40:02)
  2. 说说广场 API 0.31.0 版的调用代码说明 (2026-11-13 19:10:02)
  3. NGINX Routing on HTTP Request Body (2026-10-27 14:10:42)

查看更多 后端 文章 →

建议继续学习

  1. 使用gettext来支持PHP的多语言 (累计阅读 39,700)
  2. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,568)
  3. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,819)
  4. 我的PHP,Python和Ruby之路 (累计阅读 13,718)
  5. include(“./file.php”)和include(“file.php”)区别 (累计阅读 13,271)
  6. 15个最好的免费开源电子商务平台 (累计阅读 12,947)
  7. Redis消息队列的若干实现方式 (累计阅读 12,535)
  8. 到底什么是MVC? (累计阅读 12,383)
  9. 整理了一份招PHP高级工程师的面试题 (累计阅读 12,220)
  10. Rolling cURL: PHP并发最佳实践 (累计阅读 11,970)