一、 index.php中: ?php echo a href='process.php?filename=halo.mp3'下载/a? process.php中: ?php header(Content-type: application/octet-stream);header('Content-Disposition: attachment; filename='. basename($_GET['filename']).'');header(Cont
一、
index.php中:
<?php echo "<a href='process.php?filename=halo.mp3'>下载</a>" ?>
<?php
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="'. basename($_GET['filename']).'"');
header("Content-Length: ". filesize($_GET['filename']));
readfile($_GET['filename']);
?>二、
针对上面问题的解决方案,index.php中:
<?php echo "<a href='process.php?filename=halo光环.mp3'>下载</a>" ?>
<?php
header("Content-type: application/octet-stream");
//处理中文文件名
$ua = $_SERVER["HTTP_USER_AGENT"];
$encoded_filename = urlencode($_GET['filename']);
$encoded_filename = str_replace("+", "%20", $encoded_filename);
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header("Content-Disposition: attachment; filename*=\"utf8''" . $_GET['filename'] . '"');
} else {
header('Content-Disposition: attachment; filename="' . $_GET['filename'] . '"');
}
header("Content-Length: ". filesize($_GET['filename']));
readfile($_GET['filename']);
?>三、
立即学习“PHP免费学习笔记(深入)”;
现在貌似没有问题了,但是readfile还是有问题的,虽然PHP的readfile尝试实现的尽量高效,不占用PHP本身的内存,但是实际上它还是需要采用MMAP(如果支持),或者是一个固定的buffer去循环读取文件,直接输出。
那么能不能绕过PHP这层呢,直接由webserver把文件发送给用户呢?可以的,我们可以使用Apache的module mode_xsendfile,让Apache直接发送这个文件给用户。
代码实现如下:(process.php)
header("Content-type: application/octet-stream");
//处理中文文件名
$ua = $_SERVER["HTTP_USER_AGENT"];
$encoded_filename = urlencode($_GET['filename']);
$encoded_filename = str_replace("+", "%20", $encoded_filename);
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header("Content-Disposition: attachment; filename*=\"utf8''" . $_GET['filename'] . '"');
} else {
header('Content-Disposition: attachment; filename="' . $_GET['filename'] . '"');
}
//让Xsendfile发送文件
header("X-Sendfile: $_GET['filename']");
$type = strrchr($_GET['filename'], "."); //获取后缀
if($type == "jpg" || "png" || "gif"){
header("Content-Disposition: filename=$_GET['filename']"); //这里我试过,加引号的话,下载时会加到文件名中
header("Content-Type: image/$type");
}
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号