readfile
(PHP 4, PHP 5, PHP 7)
readfile — 输出文件
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
读取文件并写入到输出缓冲。
参数名 | 说明 |
---|---|
filename | 要读取的文件名。 |
use_include_path | 想要在 include_path 中搜索文件,可使用这个可选的第二个参数,设为 TRUE。 |
context | Stream 上下文(context) resource。 |
返回值
返回从文件中读入的字节数。如果出错返回 FALSE 并且除非是以 @readfile() 形式调用,否则会显示错误信息。
学习readfile函数的用法后,就可以实现文件下载咯
//文件下载
$file = 'monkey.jpg';
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;
}
注释
Note:
readfile() 自身不会导致任何内存问题。 如果出现内存不足的错误,使用 ob_get_level() 确保输出缓存已经关闭。
Note: 在 PHP 5.0.0 中增加了对上下文(Context)的支持。有关上下文(Context)的说明参见 Streams。