PHP下载文件

在PHP中,可使用内置的readfile()函数来实现文件下载。 readfile()函数读取一个文件并将其写入输出缓冲区。

PHP readfile()函数

语法

int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
  • $filename:表示文件名
  • $use_include_path:它是可选参数。它默认为false。可以将其设置为true以搜索included_path中的文件。
  • $context:表示上下文流资源。
  • int:它返回从文件读取的字节数。

HP下载文件示例:文本文件

在您的网站目录下(我使用的是 D:/wamp/www)创建一个文本文件: text.txt

文件: download1.php

<?php  
$file_url = 'http://localhost/text.txt';  
header('Content-Type: application/octet-stream');  
header("Content-Transfer-Encoding: utf-8");   
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");   
readfile($file_url);  
?>

PHP下载文件示例:二进制文件

文件:download2.php

<?php  
$file_url = 'http://www.myremoteserver.com/file.exe';  
header('Content-Type: application/octet-stream');  
header("Content-Transfer-Encoding: Binary");   
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");   
readfile($file_url);  
?>

上一篇: PHP上传文件 下一篇: PHP发送电子邮件(Email)