在PHP中,file()
函數(shù)用于讀取文件內(nèi)容。如果你想在文件傳輸過程中使用它,你可以通過以下方法實(shí)現(xiàn):
$filename = "example.txt";
$content = file($filename);
header("Content-Type: text/plain");
echo implode("\n", $content);
這將把名為 “example.txt” 的文件內(nèi)容作為純文本輸出。
$filename = "example.txt";
$content = file($filename);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\"");
header("Expires: 0");
header("Cache-Control: must-revalidate");
header("Pragma: public");
echo implode("\n", $content);
exit();
這將提示瀏覽器下載名為 “example.txt” 的文件。
readfile()
函數(shù)替代 file()
:readfile()
函數(shù)是專門用于讀取文件并直接輸出的函數(shù),它更簡(jiǎn)單且安全。以下是使用 readfile()
的示例:
$filename = "example.txt";
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\"");
readfile($filename);
exit();
這將提示瀏覽器下載名為 “example.txt” 的文件。
注意:在使用這些方法時(shí),請(qǐng)確保對(duì)文件進(jìn)行適當(dāng)?shù)腻e(cuò)誤檢查,例如檢查文件是否存在、是否可讀等。這可以通過 is_readable()
函數(shù)實(shí)現(xiàn)。