首页 > 语言 > PHP > 正文

利用php header函数实现文件下载保存到本地

2024-09-04 11:44:55
字体:大 中 小
来源:转载
供稿:网友

header() 函数向客户端发送原始的 http 报头,认识到一点很重要,即必须在任何实际的输出被发送之前调用 header() 函数,在 php教程 4 以及更高的版本中,您可以使用输出缓存来解决此问题,代码如下:

  1. <html> 
  2. <?php 
  3. // 结果出错 
  4. // 在调用 header() 之前已存在输出 
  5. header('location: http://www.Vevb.com/'); 
  6. ?> 

语法:header(string,replace,http_response_code)

参数 描述 

string 必需,规定要发送的报头字符串。 

replace 可选,指示该报头是否替换之前的报头,或添加第二个报头。

默认是 true(替换),false(允许相同类型的多个报头).

http_response_code 可选,把 http 响应代码强制为指定的值,php 4 以及更高版本可用.

PHP实例代码如下:

  1. <?php  
  2. function downfile() 
  3. { 
  4.  
  5.  $filename=realpath("resume.html"); 
  6.  header( "content-type:   application/octet-stream ");  
  7.  header( "accept-ranges:   bytes ");  
  8.     header( "accept-length: " .filesize($filename)); 
  9.  header( "content-disposition:   attachment;   filename= 4.html");  
  10.  echo file_get_contents($filename); 
  11.  readfile($filename);  
  12. } 
  13. downfile(); 
  14.  
  15. ?>  
  16. <?php 
  17.  
  18. function downfile($fileurl) 
  19. { 
  20. $filename=$fileurl; 
  21. $file   =   fopen($filename, "rb");  
  22. header( "content-type:   application/octet-stream ");  
  23. header( "accept-ranges:   bytes ");  
  24. header( "content-disposition:   attachment;   filename= 4.doc"); 
  25.  
  26. $contents = ""; 
  27. while (!feof($file)) { 
  28.   $contents .= fread($file, 8192); 
  29. } 
  30. echo $contents; 
  31. fclose($file); 
  32.  
  33. } 
  34. $url=$_request['url']; 
  35. $url="http://www.Vevb.com"; 
  36. downfile($url); 
  37.  
  38. ?> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表