php强制文件下载而非在浏览器打开的自定义函数分享

有时我们希望如图片、文本文档、网页、mp3、pdf等内容,当点击对应链接时直接下载,而不是在网页上显示,那么就需要强制设置header头信息。以下为一段不会产生乱码的PHP函数实现代码,其他程序语言也可参考之编写实现。

代码如下:
/**
* Downloader
*
* @param $archivo
* path al archivo
* @param $downloadfilename
* (null|string) el nombre que queres usar para el archivo que se va a descargar.
* (si no lo especificas usa el nombre actual del archivo)
*
* @return file stream
*/
function download_file($archivo,$downloadfilename = null) {

if (file_exists($archivo)) {
$downloadfilename = $downloadfilename !== null ? $downloadfilename : basename($archivo);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-disposition: attachment; filename=' . $downloadfilename);
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($archivo));

ob_clean();
flush();
readfile($archivo);
exit;
}

}

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...