首页 / PHP / 在PHP中使用Header作为下载链接
在PHP中使用Header作为下载链接
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在PHP中使用Header作为下载链接,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2321字,纯文字阅读大概需要4分钟。
内容图文
![在PHP中使用Header作为下载链接](/upload/InfoBanner/zyjiaocheng/807/9fa3ea445c9f4bebaae016a94fba3744.jpg)
所以我的下载链接有这个问题.基本上我之前创建下载链接的方法是只有一个带有method =’link’的表单按钮,并且该操作是该文件的链接.这适用于Firefox和其他人,但不适用于safari.出于某种原因,当用户尝试从safari下载文件(excel文件)时,它只会在浏览器上显示一堆ascii字符(我猜它试图用浏览器读取它?).好吧,我正在寻找另一个解决方案,似乎使用标头是这样做的方式.所以现在我尝试使用method =’post’和action =’download.php’创建一个表单按钮,其中有一个隐藏字段,其中包含指向该文件的链接.看起来像这样
function showDownloadWithHeader($link){
echo "<form action='download.php' method='post' >";
echo "<input class='downloadButton' type='submit' value='Download Report'>";
echo "<input type='hidden' name='filename' value='$link'>";
echo "</form>";
}
在download.php中我只想让用户下载该文件.
<?php
if($_POST['filename'] == '' || empty($_POST['filename'])){
exit;
}
$filename = $_POST['filename']; //the file is 2 folder down. e.g. data/stack/bla.xlsx
$file = $filename;
$extension = end(explode('.', $filename));
error_reporting(E_ALL);
ini_set("display_errors",1);
// echo $filename;
// echo "<br/>";
// echo $extension;
// echo filesize($filename);
// echo "<br/>";
switch($extension){
case 'xls':
$mimeType = 'application/vnd.ms-excel';
break;
case 'xlsx':
$mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
}
// echo $mimeType;
header('Content-Description:?File?Transfer');
header('Content-Type:?' . $mimeType);
header('Content-Disposition:?attachment;?filename='.basename($file));
header('Content-Transfer-Encoding:?binary');
header('Expires:?0');
header('Cache-Control:?must-revalidate,?post-check=0,?pre-check=0');
header('Pragma:?public');
header('Content-Length:?'?.?filesize($file));
ob_clean();
????flush();
readfile($filename);
exit;
?>
我在php.net下的readfile()函数中看到了这个解决方案,但它似乎并不适合我.我在localhost上这样做.
解决方法:
这样的事情很好.
header("Pragma: public", true);
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".basename($file));
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
die(file_get_contents($file));
内容总结
以上是互联网集市为您收集整理的在PHP中使用Header作为下载链接全部内容,希望文章能够帮你解决在PHP中使用Header作为下载链接所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。