在PHP中,您可以使用file_get_contents()
函數或fopen()
、fread()
和fclose()
函數組合來實現文件下載功能
方法1:使用file_get_contents()
函數
<?php
// 設置文件路徑
$file_path = 'path/to/your/file.txt';
// 檢查文件是否存在
if (file_exists($file_path)) {
// 設置HTTP頭信息,告訴瀏覽器這是一個文件下載請求
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
// 讀取文件并發送給瀏覽器
readfile($file_path);
// 終止腳本
exit;
} else {
echo '文件不存在';
}
?>
方法2:使用fopen()
、fread()
和fclose()
函數組合
<?php
// 設置文件路徑
$file_path = 'path/to/your/file.txt';
// 檢查文件是否存在
if (file_exists($file_path)) {
// 設置HTTP頭信息,告訴瀏覽器這是一個文件下載請求
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
// 打開文件
$handle = fopen($file_path, 'rb');
// 讀取文件內容并發送給瀏覽器
while (!feof($handle)) {
echo fread($handle, 8192);
}
// 關閉文件
fclose($handle);
// 終止腳本
exit;
} else {
echo '文件不存在';
}
?>
以上兩種方法都可以實現文件下載功能。第一種方法使用file_get_contents()
函數簡化了代碼,而第二種方法則展示了如何使用fopen()
、fread()
和fclose()
函數手動讀取文件內容。您可以根據自己的需求和喜好選擇合適的方法。