PHP header函数一此常用的用法详解

在php中header函数是一个很常用的函数了,它可以跳转也可以发送各种状态代码,如404,301或者页面编码,下面我来总结一下header函数常用方法,代码如下:

  1. <?php
  2. // fix 404 pages:
  3. header('HTTP/1.1 200 OK');
  4. // set 404 header:
  5. header('HTTP/1.1 404 Not Found');
  6. // set Moved Permanently header ('good for redrictions')
  7. // use with location header
  8. header('HTTP/1.1 301 Moved Permanently');
  9. // redirect to a new location:
  10. header('Location: http://www.phpfensi.com/');
  11. // redrict with delay:
  12. header('Refresh: 10; url=http://www.phpfensi.com/');
  13. //print You will be redirected in 10 seconds;
  14. // you could also use the HTML syntax:// <meta http-equiv="refresh" content="10;http://www.phpfensi.com/ />
  15. // override X-Powered-By: PHP:
  16. header('X-Powered-By: PHP/4.4.0');
  17. header('X-Powered-By: Brain/0.6b');
  18. // content language ('en = English')
  19. header('Content-language: en');
  20. // last modified ('good for caching')
  21. $time = time('') – 60; // or filemtime('$fn'), etc
  22. header('Last-Modified: .gmdate("D, d M Y H:i:s, ' . $time . '"). GMT');
  23. // header for telling the browser that the content
  24. // did not get changed
  25. header('HTTP/1.1 304 Not Modified');
  26. // set content length ('good for caching'):
  27. header('Content-Length: 1234');
  28. // Headers for an download:
  29. header('Content-Type: application/octet-stream');
  30. header('Content-Disposition: attachment; filename="example.zip"');
  31. header('Content-Transfer-Encoding: binary');
  32. // load the file to send:readfile('example.zip');
  33. // Disable caching of the current document:
  34. header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
  35. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  36. // Date in the pastheader('Pragma: no-cache');
  37. // plain text file
  38. header('Content-Type: image/jpeg');
  39. // JPG picture
  40. header('Content-Type: application/zip');
  41. // ZIP file
  42. header('Content-Type: application/pdf');
  43. // PDF file
  44. header('Content-Type: audio/mpeg');
  45. // Audio MPEG ('MP3,…') file
  46. header('Content-Type: application/x-shockwave-flash');
  47. // Flash animation// show sign in box
  48. header('HTTP/1.1 401 Unauthorized');
  49. header('WWW-Authenticate: Basic realm="Top Secret"');
  50. //print Text that will be displayed if the user hits cancel or ;
  51. //print enters wrong login data;
  52. // set content type:
  53. header('Content-Type: text/html; charset=iso-8859-1');
  54. header('Content-Type: text/html; charset=utf-8');
  55. header('Content-Type: text/plain');
  56. php页面为utf编码
  57. header("Content-type: text/html; charset=utf-8");
  58. php页面为gbk编码
  59. header("Content-type: text/html; charset=gb2312");
  60. php页面为big5编码
  61. header("Content-type: text/html; charset=big5");
  62. Header( "HTTP/1.1 301 Moved Permanently" ) ;
  63. Header( "Location: www.phpfensi.com" );
  64. ?>