浏览器下载文件,PHP服务器端的处理

  在做Web开发时,用户下载附件是经常遇到的一种情况。在HTML页面中,我们只要给个链接就可以了,但在服务器端要做怎样的处理呢?

 

   以下的代码是用PHP语言写的,当用户用浏览器下载文件时,服务端所要做的处理。不管用Java还是.Net,基本原理是一样的,涉及的都是关于Http协议。





$file_path = ROOT_PATH . '/uploads/accessories/'. $_GET ['name'];//文件的物理路径。一般来说,我们都是把文件(Excel、Word)直接存在硬盘上,而不是数据库

header ( 'Content-Disposition: attachment; filename=' . urlencode ( $_GET ['filename'] ) );//如果文件名是中文的, urlencode 之后在IE不会出现中文乱码

header ( 'Content-type: application/octet-stream;' );

header ( 'Content-Length: ' . filesize ( $file_path ) );//文件的大小

readfile ( $file_path );

exit ();

 

PS:简单补充一下HTTP协议的简单介绍:

http://www.cnblogs.com/skynet/archive/2010/12/11/1903347.html

 

原文链接:http://woqilin.blogspot.com/2012/09/php_12.html

猜你喜欢

转载自wangzq-phper.iteye.com/blog/2294214
今日推荐