readfile 输出文件

发表日期:2021-07-01 08:55:44 | 来源: | | 浏览(774) 分类:文件系统函数

readfile

(PHP 4, PHP 5, PHP 7, PHP 8)

readfile输出文件

说明

readfile(string $filename, bool $use_include_path = false, resource $context = ?): int

读取文件并写入到输出缓冲。

参数


  • filename

  • 要读取的文件名。

  • use_include_path

  • 想要在   include_path   中搜索文件,可使用这个可选的第二个参数,设为 true

  • context

  • Stream 上下文(context) resource


返回值

成功时返回从文件中读入的字节数, 或者在失败时返回 false  

错误/异常

失败时抛出E_WARNING警告。

范例


示例 #1 使用 readfile() 强制下载

<?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('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

以上例程的输出类似于:

e88cefb5c3fca5060e2490b9763c4433-readfile.png


注释

注意:

readfile() 自身不会导致任何内存问题。    如果出现内存不足的错误,使用 ob_get_level() 确保输出缓存已经关闭。


小技巧

如已启用fopen 包装器,在此函数中, URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议,注意其用法及其可提供的预定义变量。

注意: 在 PHP 5.0.0 中增加了对上下文(Context)的支持。有关上下文(Context)的说明参见 Streams。

参见


  • fpassthru() - 输出文件指针处的所有剩余数据

  • file() - 把整个文件读入一个数组中

  • fopen() - 打开文件或者 URL

  • include - include

  • require - require

  • virtual() - 执行 Apache 子请求

  • file_get_contents() - 将整个文件读入一个字符串

  • 支持的协议和封装协议


集速网 copyRight © 2015-2022 宁ICP备15000399号-1 宁公网安备 64010402001209号
与其临渊羡鱼,不如退而结网
欢迎转载、分享、引用、推荐、收藏。