要在PHP中下载文件,我们需要强制浏览器下载除显示之外的文件。
在本文中,我们将展示如何从PHP中从目录或者服务器下载文件。
使用'head()'和'readfile()'函数,我们可以轻松下载PHP中的文件。
其中我们将提供示例PHP代码以强制PHP中的下载文件。
此外,这个简单的PHP脚本有助于实现从目录下载文件的下载链接。
以下示例脚本可用于下载文本,图像,文档,PDF,Zip等的任何类型的文件。
在PHP中下载文件
$fileName = basename('onitroad.txt');
$filePath = 'files/'.$fileName;
if(!empty($fileName) && file_exists($filePath)){
//Define headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$fileName");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
//Read the file
readfile($filePath);
exit;
}else{
echo 'The file does not exist.';
}
通过锚链接下载文件
有时我们需要提供与服务器下载文件的链接。
使用以下示例代码显示HTML链接以使用PHP从目录下载文件。
HTML代码:
<a href="download.php?file=onitroad.png">Dowload File</a>
PHP代码(Download.php):
<?php
if(!empty($_GET['file'])){
$fileName = basename($_GET['file']);
$filePath = 'files/'.$fileName;
if(!empty($fileName) && file_exists($filePath)){
//Define headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$fileName");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
//Read the file
readfile($filePath);
exit;
}else{
echo 'The file does not exist.';
}
}
日期:2020-06-02 22:15:30 来源:oir作者:oir
