手机
当前位置:查字典教程网 >编程开发 >php教程 >php强制文件下载而非在浏览器打开的自定义函数分享
php强制文件下载而非在浏览器打开的自定义函数分享
摘要:有时我们希望如图片、文本文档、网页、mp3、pdf等内容,当点击对应链接时直接下载,而不是在网页上显示,那么就需要强制设置header头信息...

有时我们希望如图片、文本文档、网页、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;

}

}

【php强制文件下载而非在浏览器打开的自定义函数分享】相关文章:

php支持中文字符串分割的函数

PHP中生成UUID自定义函数分享

自定义PHP分页函数

php实现将上传word文件转为html的方法

php使用curl打开https网站的方法

建立文件交换功能的脚本(二)

php以fastCGI的方式运行时文件系统权限问题及解决方法

php实现统计网站在线人数的方法

PHP4引用文件语句的对比

一个多文件上传的例子(原创)

精品推荐
分类导航