在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)