Useful PHP Header Download function

Source: Internet
Author: User
  1. /**

  2. * Send File
  3. *
  4. * @param string $fileName file name or path
  5. * @param string $fancyName A custom file name, or null to use filename
  6. * @param boolean $forceDownload whether to force download
  7. * @param integer $speedLimit speed limit in bytes, 0 is unrestricted, Windows Server is not supported
  8. * @param string $ $contentType file type, default is Application/octet-stream
  9. *
  10. * @return Boolean
  11. */
  12. function SendFile ($fileName, $fancyName = ", $forceDownload = true, $speedLimit = 0, $contentType =")
  13. {
  14. if (!is_readable ($fileName))
  15. {
  16. Header ("http/1.1 404 Not Found");
  17. return false;
  18. }
  19. $fileStat = stat ($fileName);
  20. $lastModified = $fileStat [' Mtime '];

  21. $MD 5 = MD5 ($fileStat [' mtime ']. ' ='. $fileStat [' ino ']. ' ='. $fileStat [' size ']);

  22. $etag = ' "'. $MD 5. '-' . CRC32 ($MD 5). '"';
  23. Header (' last-modified: '. Gmdate ("D, D M Y h:i:s", $lastModified). ' GMT ');
  24. Header ("ETag: $etag");

  25. if (Isset ($_server[' http_if_modified_since ')) && strtotime ($_server[' http_if_modified_since ']) >= $ LastModified)

  26. {
  27. Header ("http/1.1 304 not Modified");
  28. return true;
  29. }
  30. if (Isset ($_server[' http_if_unmodified_since ')) && strtotime ($_server[' http_if_unmodified_since ']) < $ LastModified)
  31. {
  32. Header ("http/1.1 304 not Modified");
  33. return true;
  34. }
  35. if (Isset ($_server[' Http_if_none_match ')) && $_server[' http_if_none_match '] = = $etag)
  36. {
  37. Header ("http/1.1 304 not Modified");
  38. return true;
  39. }
  40. if ($fancyName = = ")
  41. {
  42. $fancyName = basename ($fileName);
  43. }

  44. if ($contentType = = ")

  45. {
  46. $contentType = ' Application/octet-stream ';
  47. }
  48. $fileSize = $fileStat [' Size '];

  49. $contentLength = $fileSize;

  50. $isPartial = false;
  51. if (Isset ($_server[' Http_range '))
  52. {
  53. if (Preg_match ('/^bytes= (d*)-(d*) $/', $_server[' Http_range '], $matches))
  54. {
  55. $startPos = $matches [1];
  56. $endPos = $matches [2];
  57. if ($startPos = = "&& $endPos = =")
  58. {
  59. return false;
  60. }

  61. if ($startPos = = ")

  62. {
  63. $startPos = $fileSize-$endPos;
  64. $endPos = $fileSize-1;
  65. }
  66. else if ($endPos = = ")
  67. {
  68. $endPos = $fileSize-1;
  69. }
  70. $startPos = $startPos < 0? 0: $startPos;
  71. $endPos = $endPos > $fileSize-1? $fileSize-1: $endPos;
  72. $length = $endPos-$startPos + 1;
  73. if ($length < 0)
  74. {
  75. return false;
  76. }
  77. $contentLength = $length;
  78. $isPartial = true;
  79. }
  80. }

  81. Send headers

  82. if ($isPartial)
  83. {
  84. Header (' http/1.1 206 Partial Content ');
  85. Header ("Content-range:bytes $startPos-$endPos/$fileSize");

  86. }

  87. Else
  88. {
  89. Header ("http/1.1 OK");
  90. $startPos = 0;
  91. $endPos = $contentLength-1;
  92. }
  93. Header (' Pragma:cache ');
  94. Header (' Cache-control:public, must-revalidate, max-age=0 ');
  95. Header (' accept-ranges:bytes ');
  96. Header (' Content-type: '. $contentType);
  97. Header (' Content-length: '. $contentLength);

  98. if ($forceDownload)

  99. {
  100. Header (' content-disposition:attachment; Filename= '. Rawurlencode ($fancyName). ' "');//kanji automatically to URL encoding
  101. Header (' content-disposition:attachment; Filename= '. $fancyName. '"');
  102. }
  103. Header ("Content-transfer-encoding:binary");
  104. header function Implementation file download

  105. $bufferSize = 2048;

  106. if ($speedLimit! = 0)
  107. {
  108. $packetTime = Floor ($bufferSize * 1000000/$speedLimit);
  109. }
  110. $bytesSent = 0;
  111. $fp = fopen ($fileName, "RB");
  112. Fseek ($fp, $startPos);
  113. Fpassthru ($FP);

  114. while ($bytesSent < $contentLength &&!feof ($fp) && connection_status () = = 0)

  115. {
  116. if ($speedLimit! = 0)
  117. {
  118. List ($usec, $sec) = Explode ("", Microtime ());
  119. $outputTimeStart = ((float) $usec + (float) $sec);
  120. }//Bbs.it-home.org
  121. $readBufferSize = $contentLength-$bytesSent < $bufferSize? $contentLength-$bytesSent: $bufferSize;
  122. $buffer = Fread ($fp, $readBufferSize);
  123. Echo $buffer;
  124. Ob_flush ();
  125. Flush ();
  126. $bytesSent + = $readBufferSize;

  127. if ($speedLimit! = 0)

  128. {
  129. List ($usec, $sec) = Explode ("", Microtime ());
  130. $outputTimeEnd = ((float) $usec + (float) $sec);

  131. $useTime = ((float) $outputTimeEnd-(float) $outputTimeStart) * 1000000;

  132. $sleepTime = Round ($packetTime-$useTime);
  133. if ($sleepTime > 0)
  134. {
  135. Usleep ($sleepTime);
  136. }
  137. }
  138. }
  139. return true;
  140. }
  141. ?>

Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.