yxsailing 发表于 2017-12-30 21:46:06

用PHP实现浏览器点击下载各种格式文档的方法详解【txt apk等等】

  PHP代码如下:
  ===========================================================
  $filename = '/path/'.$_GET['file'].'.txt'; //文件路径
  header("Content-Type: application/force-download");
  header("Content-Disposition: attachment; filename=".basename($filename));【注,测经验basename()不支持中文】
  readfile($filename);
  ===========================================================
  简要说明:
  第一个header函数设置Content-Type的值为application/force-download;
  第二个header函数设置要下载的文件。注意这里的filename是不包含路径的文件名,filename的值将来就是点击下载后弹出对话框里面的文件名,如果带路径的话,弹出对话框的文件名就是未知的;
  最后通过readfile函数,将文件流输出到浏览器,这样就实现了txt文件的下载。
  [无意中发现,如果在此文件中输出内容,这些内容会被写入到下载文件中]
  第二部分:手机调用php页面,实现apk的下载
  关键:header('application/vnd.android.package-archive');//android包apk下载 的专属头文件
  

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

  header("Content-Length: " . filesize($filename)); //这个头文件是为了下载时显示文件大小的,如果没有此头部,(手机)下载时不会显示大小
  header("Content-Disposition: attachment; filename=".basename($filename));
  readfile($filename);
  【新增】
  

$file = 'sf.jpg';  
if (file_exists($file)) {
  
header('Content-Description: File Transfer');
  
header('Content-Type: application/octet-stream');
  
header('Content-Disposition: attachment; filename="'.basename($file).'"');
  
header('Expires: 0');
  
header('Cache-Control: must-revalidate');
  
header('Pragma: public');
  
header('Content-Length: ' . filesize($file));
  
readfile($file);
  
exit;
  
}
  

  <?php


[*]header("Content-Type:text/html; ");
[*]if(get_device_type()=='ios'){
[*]$ff='huanbaoba.ipa';
[*]    header('application/iphone');ios专属现在头文件
[*]    header('Content-Disposition:attachment;filename="huanbaoba.ipa"');
[*]}else{
[*]$ff='huanbaoba.apk';
[*]    header('application/vnd.android.package-archive');
[*]    header('Content-Disposition:attachment;filename="huanbaoba.apk"');
[*]}
[*]readfile($ff);
[*]//获取设备类型
[*]function get_device_type(){
[*]$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
[*]$type = 'other';
[*]if(strpos($agent, 'iphone') || strpos($agent, 'ipad')){
[*]$type = 'ios';
[*]    }
[*]if(strpos($agent, 'android')){
[*]$type = 'android';
[*]    }
[*]return $type;
[*]}
  第三部分:js 或者 php如何获取设备或者浏览器类型,如是否是在微信中打开的等等
  一:js判断设备类型


[*]function is_weixn(){
[*]    var ua = navigator.userAgent.toLowerCase();
[*]    if(ua.match(/MicroMessenger/i)=="micromessenger") {//判断是否在微信中打开此网页
[*]      return true;
[*]    } else {
[*]      return false;
[*]    }
[*]}
  二: php判断设备及浏览器等等类型


[*]function is_weixin(){
[*]    if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
[*]            return true;
[*]    }
[*]    return false;
[*]}
页: [1]
查看完整版本: 用PHP实现浏览器点击下载各种格式文档的方法详解【txt apk等等】